23 BSTs
23 BSTs
1
Binary Search Trees Invalid BSTs
• The binary-search-tree property
o If node y in left subtree of node x, then key[y] ≤ key[x].
o If node y in right subtree of node x, then key[y] ≥ key[x].
• Binary search trees are an important data
structure that supports dynamic set
operations:
o Search, Minimum, Maximum, Predecessor, Successor,
Insert, and Delete.
o Basic operations take time proportional to the height of
the tree – O(h).
• Q: Where is the minimum/maximum key?
30 55
25 53 60
35
10
31 62
37
20 Inorder-Tree-Walk (x)
1. if x ≠ NIL
Prints out keys in sorted order: 2. then Inorder-Tree-Walk(left[x])
10, 20, 25, 30, 31, 35, 37, 50, 53, 55, 60, 62 3. print key[x]
4. Inorder-Tree-Walk(right[x])
2
Iterative Tree Search Finding Min & Max
Search for 37 < 50 • The binary-search-tree property guarantees that:
≥ Running time O(h) o The minimum is located at the left-most node.
where h is tree height
< 30 55 o The maximum is located at the right-most node.
< ≥
≥
Tree-Minimum(x) Tree-Maximum(x)
< 25 53 60 1. while left[x] ≠ NIL 1. while right[x] ≠ NIL
35 ≥
< 2. do x ← left[x] 2. do x ← right[x]
≥ 3. return x 3. return x
10
≥ 62
31 37
Iterative-Tree-Search(x, k) o Question: how long do they take?
20 1. while x ≠ NIL and k ≠ key[x]
2. do if k < key[x]
3. then x ← left[x]
4. else x ← right[x]
5. return x
3