Lecture 09 - Binary Search Trees
Lecture 09 - Binary Search Trees
• Homework 1 Statistics
• Mean: 39.7/50 (+1 extra credit)
• Median: 42.5/50 (+0 extra credit)
• Max: 49/50 (+1) or 47/50 (+4)
• Standard Deviation: 10.18
Reminder: Tree terminology
Node / Vertex
A Root
B C
Left subtree
Right subtree
D E F G
Edges H I Leaves
J K L M N
Binary Trees
• Binary tree: Each node has at most 2 children (branching factor 2)
• Binary tree is
• A root (with data)
• A left subtree (may be empty)
• A right subtree (may be empty)
• Special Cases:
(Last week’s practice) What does the following method do?
int height(Node root){
if (root == null),
return -1;
return 1 + max(height(root.left),
height(root.right);
}
• min # of leaves:
• min # of nodes:
B C
• In-order: left subtree, root, right subtree
D E F
• Post-order: left subtree, right subtree, root
G
Tree Traversals: Practice
Which one makes sense for evaluating this expression tree?
4 7 9 14
• Result: straight-forward to find any given value
13
5 8
4 8 5 11
1 7 11 2 7 6 10 18
3 4 15 20
21
How do we find(value) in BST’s?
12
5 15
2 9 20
7 10 17 30
find in BST: Recursive Version
Data find(Data value, Node root){
if(root == null)
12 return null;
if(key < root.value)
return find(value, root.left);
if(key > root.value)
5 15 return find(value, root.right);
return root.value;
}
2 9 20
What is the running time?
7 10 17 30
find in BST: Iterative Version
5 15
7 10 17 30
insert in BST
12 insert(13)
insert(8)
insert(31)
5 15
2 9 20
• Basic idea:
delete(17) 12
5 15
2 9 20
7 10 17 30
delete case: One Child
delete(15) 12
5 15
2 9 20
7 10 30
delete case: Two Children
delete(5) 12
What can we 5
replace 5 with?
2 9 20
7 10 30
delete case: Two Children
What can we replace the node with?
Options:
delete case: Two Children (example #2)
delete(23) 12
5 23
2 9 18 30
7 10 15 19 25 32
Practice with insert, primer for delete
Changing as few nodes as possible, delete the following in order:
42, 14
14
2 20
1 5 16 42
4
delete through Lazy Deletion
• Lazy deletion can work well for a BST
• Simpler
• Can do “real deletions” later as a batch
• Some inserts can just “undelete” a tree node
• But
• Can waste space and slow down find operations
• Make some operations more complicated:
• e.g., findMin and findMax?
buildTree for BST
Let’s consider buildTree (insert values starting from an empty tree)