CS 46B  Lecture 24
Preclass reading
Binary Search Trees
 Fast set implementation
 Motivated by binary search
 Binary search looks either in left or right interval, O(log n)
 BST property: For each node
 The data values of all descendants to the left are less than the data value stored in the node, and all descendants to the right have greater data values.
A Binary Search Tree
A Tree That is Not a BST
Insertion
Lecture 24 Clicker Question 1
Which tree is the result of inserting F R E D into an empty binary search tree

F
/ \
D R
\
E

F
\
R
/
E
/
D

F
/ \
E R
/
D
 Something else
Implementation of Insertion
class Node
{
. . .
public void addNode(Node newNode)
{
int comp = newNode.data.compareTo(data);
if (comp < 0)
{
if (left == null) { left = newNode; }
else { left.addNode(newNode); }
}
else if (comp > 0)
{
if (right == null) { right = newNode; }
else { right.addNode(newNode); }
}
}
. . .
}
Finding an Element
 Does it equal the root element?
 If so, congratulationsâ€”you found it
 If not, go to the left subtree
 Otherwise, go to the right subtree
 Just like binary search
 O(log n) provided the tree is balanced
Lecture 24 Clicker Question 2
Assume 1000 random integers were inserted into a BST. Approximately how many comparison are needed to find whether the integer 42 is among them?
 1000
 512
 10
 1
Removal
 Need to find the element to remove
 ...and its parent
 If the element to be removed is leaf, just remove it
 If the element to be removed has only one child, just use that.
Removal
 Hard part: Removing node with two children
 Find smallest child in right subtree
 That node has at most one child
 Remove it (see previous slide)
 Copy its value to the node to be removed
Lecture 24 Clicker Question 3
Consider this BST:
C
/ \
A G
/ \
D K
What is the result of removing C?

G
/ \
A K
/
D

A
\
G
/ \
D K

D
/ \
A G
\
K
 Someting else
Efficiency
 Assumption: Balanced tree
 Finding an element: O(log n)
 Adding an element
 Follow path from root to leaf
 Path length is O(log n)
 Removing an element
 Finding node to be removed: O(log n)
 Finding smallest child in right subtree: O(log n)
 Next semester: Can rebalance tree in guaranteed O(log n) time
Lecture 24 Clicker Question 4
You need to keep a set of lots of objects of class X. You don't care about traversal in sorted order, but you want maximum efficiency. What should you choose, and why?
 A hash table because its add/remove/find operations are O(1)+
 A rebalancing BST because its add/remove/find operations are guaranteed to be O(log n)
 A hash table because it is easier to come up with a hashCode method for X than a compareTo method
 A rebalancing BST because it is easier to come up with a compareTo method for X than a hashCode method