Binary Search Trees: COL 106 Amit Kumar and Shweta Agrawal
Binary Search Trees: COL 106 Amit Kumar and Shweta Agrawal
Binary Search Trees: COL 106 Amit Kumar and Shweta Agrawal
COL 106
Amit Kumar and Shweta Agrawal
B C
Left subtree
Right subtree
D E F G
Edges H I Leaves
J K L M N
Order: A B H C D G I E F J K
8
Breadth-First Traversal
Breadth-first traversals visit all nodes at a given
depth
– Memory: max nodes at given depth
• Order property 5 11
– All keys in left subtree smaller
than node’s key
– All keys in right subtree larger 2 6 10 12
than node’s key
– Result: easy to find any given key
4 7 9 14
5 8
4 8 5 11
1 7 11 2 7 6 10 18
3 4 15 20
21
CSE373: Data Structures &
Winter 2015 13
Algorithms
Examples
Here are other examples of binary search trees:
Examples
Unfortunately, it is possible to construct degenerate
binary search trees
1 2 3 4
CSE373: Data Structures &
Winter 2015 22
Algorithms
Find in BST, Iterative
12 Data find(Key key, Node root){
while(root != null
&& root.key != key) {
5 15 if(key < root.key)
root = root.left;
else(key > root.key)
2 9 20 root = root.right;
}
if(root == null)
7 10 17 30 return null;
return root.data;
}
5 15
• FindMax: Find maximum node
– Right-most node 2 9 20
7 10 17 30
• But
– Can waste space and slow down find operations
– Make some operations more complicated:
• e.g., findMin and findMax?