Binary Search Trees - PowerPoint PPT Presentation

1 / 17
About This Presentation
Title:

Binary Search Trees

Description:

BST trees can vary greatly in their degree of balance. Example that follows shows two BST trees with the same set of keys, one is ... – PowerPoint PPT presentation

Number of Views:64
Avg rating:3.0/5.0
Slides: 18
Provided by: IRE62
Category:
Tags: binary | bst | search | trees

less

Transcript and Presenter's Notes

Title: Binary Search Trees


1
Binary Search Trees
  • Irena Pevac
  • CS501

2
BST
  • Binary Search Tree is special type of a binary
    tree where keys come from an ordered set. For
    every node all keys in a left subtree are less
    than or equal to the key in a node and all keys
    in the right subtree are larger than the key in a
    node.

3
BST Properties
  • An inorder traversal of a BST produces a sorted
    list of keys.
  • BST trees can vary greatly in their degree of
    balance.
  • Example that follows shows two BST trees with the
    same set of keys, one is balanced and other is
    not.

4
Two BSTs
5
Basic Operations
  • Search
  • To search for an item we move through one path in
    the tree and if successful we will find it
    somewhere on that path if not we stop when we
    reach a leaf node.
  • Insert
  • To insert an item we move through one path in the
    tree and insert new item as a leaf.
  • Delete
  • Delete a leaf
  • Delete a node with one empty subtree
  • Delete a node with two nonempty subtrees

6
Delete a Leaf
  • Make a reference from the parent of the node to
    be deleted to be null.

7
Leaf Deleted
8
Delete a Node With One Child
9
Node With One Child Deleted
10
Delete a Node With Two Children
11
Find Smallest in Right Subtree
12
Node With Two Children Deleted
13
BST Search
  • Element bstSearch(BinTree bst, Key K)
  • Element found
  • if (bst nil)
  • found null
  • else
  • Element root root(bst)
  • If (K root.key)
  • found root
  • else if (K lt root.key)
  • found bstSearch (leftSubtree(bst), K)
  • else
  • found bstSearch(rightSubtree(bst), K)
  • return found

14
Analysis of Binary Search Tree Search
  • Basic operation the number of internal nodes of
    the tree that are examined while searching for a
    key. Comparing a key twice is counted as a two
    way comarison.
  • For unbalaced BST, cost is ?(n)
  • For a balanced BST, cost is ?(lg n)
  • We try to make the tree balanced using
    technique of binary tree rotations

15
Rotation
  • Rotation involves a group of two connected nodes,
    say p, and c for parent and child.

16
Binary Tree Rotations
17
Left Rotation
  • In a left rotation p is to the left of c.
  • Node p sinks
  • Node c rises
  • The edge to the middle subtree moves to the left
    to hook up with p.
  • The left principal subtree sinks along with p.
  • The right principal subtree rises along with c.
  • The middle principal subtree remains on the same
    level.
Write a Comment
User Comments (0)
About PowerShow.com