Sub topic 3
Inorder traversal yields sorted keys
This chapter assumes you know recursion, object references, Big-O notation, and the four traversals of a binary tree. It covers the BST ordering property, deletion, operation cost, Catalan counting, and AVL balancing.
Inorder traversal yields sorted keys
In a binary search tree (BST), every key in a node's left subtree is smaller than the node's key, and every key in its right subtree is larger. Inorder traversal visits the left subtree, then the node, then the right subtree. Because of the ordering property, an inorder traversal of any BST lists its keys in ascending order.
Deleting from a BST
Deletion has three cases. A leaf is removed directly. A node with one child is replaced by that child. A node with two children takes the value of its inorder successor, the smallest key in its right subtree, and that successor is then deleted from the right subtree.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def delete(node, key):
if node is None:
return None
if key < node.key:
node.left = delete(node.left, key)
elif key > node.key:
node.right = delete(node.right, key)
else:
if node.left is None:
return node.right
if node.right is None:
return node.left
succ = node.right
while succ.left:
succ = succ.left
node.key = succ.key
node.right = delete(node.right, succ.key)
return nodeCost of BST operations and the role of height
Search, insertion, and deletion each follow one path from the root downward. The cost of each is O(h), where h is the height of the tree.
- Balanced tree with n keys: h is about log2(n), so the cost is O(log n).
- Skewed tree with n keys: h is n − 1, so the cost is O(n).
Counting BSTs with Catalan numbers
The number of structurally distinct BSTs on n keys is the nth Catalan number:
C(n) = (1 / (n + 1)) × binomial(2n, n)
Equivalently, C(0) = 1 and C(n) = sum of C(i) × C(n − 1 − i) for i from 0 to n − 1. The first values are 1, 1, 2, 5, 14. For n = 3, there are 5 distinct BSTs.
Keeping a BST balanced: AVL trees
An AVL tree stores the height difference between each node's subtrees. This balance factor must stay within −1, 0, or 1. After an insertion or deletion breaks this rule, the tree applies one or two rotations to restore it. Rotations keep the inorder order unchanged while lowering the height, so every operation stays O(log n).
Exercise
Exercise
A BST has 4 keys. How many distinct BSTs can store them?
Show answer
C(4) = (1 / 5) × binomial(8, 4) = 70 / 5 = 14.