Trees & BST, Part 2: Balanced Trees & Trie
sortedcontainers.SortedList gets a similar result with a different structure. A Trie is a tree of letters, used for autocomplete. Last, an expression tree is a tree that holds a formula, and postorder is the traversal that evaluates it.After this lesson, you will be able to:
- Implement BST `delete` correctly across all three cases (leaf, one child, two children)
- Write `is_valid_bst` using lower and upper bounds, and explain why checking only parent and child is not enough
- Explain why AVL and Red-Black trees keep the height near log n, and when to use `sortedcontainers.SortedList` instead
- Build a Trie that finds words by prefix in O(L), where L is the length of the prefix, and use postorder to evaluate expression trees
Before you start
#BST Delete: The Hardest BST Operation
Delete has three cases that must be handled in order:
- Leaf node. Just remove it (the parent's link to it becomes None)
- One child. Replace the node with its only child
- Two children. Replace the node's value with its inorder successor, then delete the successor. The inorder successor is the next larger value in the tree, which is the smallest value in the right subtree. Deleting it is always Case 1 or Case 2.
from __future__ import annotations
from typing import Any, Optional, Tuple
class BSTNode:
def __init__(self, val: Any) -> None:
self.val = val
self.left: Optional[BSTNode] = None
self.right: Optional[BSTNode] = None
class BST:
def __init__(self) -> None:
self.root: Optional[BSTNode] = None
self._size: int = 0
# (insert/search/min from Part 1 omitted for brevity)
def _min_node(self, node: BSTNode) -> BSTNode:
"""Helper: return the node with minimum value in a subtree."""
while node.left is not None:
node = node.left
return node
def delete(self, val: Any) -> None:
"""
Delete val from the BST. Three cases:
1. Node is a leaf: just remove it
2. Node has ONE child: replace node with that child
3. Node has TWO children: replace its value with the inorder successor
(smallest value in the right subtree), then delete the successor
O(h).
"""
self.root, deleted = self._delete_recursive(self.root, val)
if deleted:
self._size -= 1
def _delete_recursive(
self, node: Optional[BSTNode], val: Any
) -> Tuple[Optional[BSTNode], bool]:
"""Returns (new_subtree_root, was_deleted)."""
if node is None:
return None, False # value not found
deleted = False
if val < node.val:
node.left, deleted = self._delete_recursive(node.left, val)
elif val > node.val:
node.right, deleted = self._delete_recursive(node.right, val)
else:
# Found the node to delete
deleted = True
# Case 1: Leaf node, just remove it
if node.left is None and node.right is None:
return None, True
# Case 2a: Only a right child exists, replace with it
if node.left is None:
return node.right, True
# Case 2b: Only a left child exists, replace with it
if node.right is None:
return node.left, True
# Case 3: Two children
# Find the INORDER SUCCESSOR: smallest value in the right subtree
# Why the inorder successor? It is the next larger value, so the BST rule still holds
successor = self._min_node(node.right)
node.val = successor.val # copy successor's value into current node
# Delete the successor from the right subtree
node.right, _ = self._delete_recursive(node.right, successor.val)
return node, deleted#Why the Inorder Successor Works for Case 3
When you delete a node with two children, you need a replacement that keeps the BST rule: greater than everything in the left subtree, less than everything in the right subtree. The two valid choices are:
- The inorder successor: smallest value in the right subtree (next larger value)
- The inorder predecessor: largest value in the left subtree (next smaller value)
Either works. Most implementations pick the successor by convention.
#Delete Case Visualization
The inorder successor of 5 is 6, the smallest value in the right subtree. Copy 6 into the node being deleted. Then delete the original 6 node from the right subtree, which is a leaf (Case 1) or has one child (Case 2).
Case 3 ends by calling _delete_recursive again on the right subtree. Could that recursive call itself hit Case 3, and recurse again?
#BST Validation: The Cross-Level Bounds Bug
is_valid_bst checks only a node against its direct children, and it gives the wrong answer on trees that are invalid in a less obvious way.#Why the Bug Exists
max_val shrinks when you go left, and min_val grows when you go right.#k-th Smallest: Using the Sorted Order of Inorder
def kth_smallest(self, k: int) -> Any:
"""
Return the k-th smallest element (1-indexed).
Uses inorder traversal and stops early after k nodes.
O(h + k) time, O(h) space for the call stack.
"""
count = [0]
result = [None]
def _inorder(node):
if node is None or count[0] >= k:
return
_inorder(node.left)
count[0] += 1
if count[0] == k:
result[0] = node.val
return
_inorder(node.right)
_inorder(self.root)
if result[0] is None:
raise ValueError(f"k={k} is out of range")
return result[0]The trick: inorder visits values in sorted order, so the k-th node visited is the k-th smallest. Count the visits and stop as soon as you reach k.
`kth_smallest` is O(h + k), not O(n). Which part of the code buys that, and what would you lose by deleting it?
#Self-Balancing: AVL Trees (Conceptual)
#The AVL Balance Factor
balance_factor(node) = height(node.left) - height(node.right)
# Must be -1, 0 or +1 for the AVL rule to hold.
# +1: left side taller | 0: balanced | -1: right side taller
#The Four Rotation Cases
| Case | Detection | Fix |
|---|---|---|
| Left-Left (LL) | New node added under the left child's left side | rotate_right(node) |
| Left-Right (LR) | New node added under the left child's right side | rotate_left(node.left) then rotate_right(node) |
| Right-Right (RR) | New node added under the right child's right side | rotate_left(node) |
| Right-Left (RL) | New node added under the right child's left side | rotate_right(node.right) then rotate_left(node) |
#Example: RR Imbalance
Inserting 1, 2, 3 into an AVL tree:
rotate_left(1):#AVL vs Red-Black Trees
| Criteria | AVL | Red-Black |
|---|---|---|
| Balance rule | Stricter (balance factor -1, 0 or +1) | Looser (the longest path is at most twice the shortest) |
| Lookup speed | Faster (shorter tree) | Slightly slower |
| Insert and delete | More rotations | Fewer rotations |
| Best for | Mostly reading | Mostly writing (Linux kernel, Java TreeMap) |
#In Python: Just Use sortedcontainers.SortedList
sortedcontainers.SortedList. It keeps a list of sorted sublists instead of a tree, so most of its work uses fast built-in list operations:from sortedcontainers import SortedList
sl = SortedList()
sl.add(5); sl.add(3); sl.add(7); sl.add(1)
print(list(sl)) # [1, 3, 5, 7] always sorted
print(sl.bisect_left(4)) # 2 O(log n) binary search
sl.discard(3) # O(log n) delete
print(sl.count(5)) # 1 O(log n)SortedList whenever you need a sorted collection with fast operations in everyday Python. Write an AVL tree yourself only to learn, or when you need your own comparison rules.The table says AVL is for read-heavy work and Red-Black for write-heavy, yet AVL has the stricter balance rule. Why does being stricter make it worse for writes?
#Trie: The Prefix Tree
Trie After Inserting 'cat', 'car', 'card', 'care'
from typing import List, Optional
class TrieNode:
"""A node in a Trie. Each node stores its children in a dict."""
def __init__(self) -> None:
self.children: dict[str, TrieNode] = {}
self.is_end: bool = False # True if a complete word ends here
class Trie:
"""
Prefix tree for string operations.
All operations are O(L) where L = length of the string.
Uses: autocomplete, spell-check.
"""
def __init__(self) -> None:
self.root = TrieNode()
def insert(self, word: str) -> None:
"""O(L) where L = len(word)."""
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
def search(self, word: str) -> bool:
"""Exact word match. Both the path AND is_end must be True. O(L)."""
node = self._traverse(word)
return node is not None and node.is_end
def starts_with(self, prefix: str) -> bool:
"""Any word starts with prefix. Only path needs to exist. O(L)."""
return self._traverse(prefix) is not None
def _traverse(self, text: str) -> Optional[TrieNode]:
node = self.root
for char in text:
if char not in node.children:
return None
node = node.children[char]
return node
def autocomplete(self, prefix: str) -> List[str]:
"""All words starting with prefix. O(L + W) where W = total chars in matches."""
node = self._traverse(prefix)
if node is None:
return []
results: List[str] = []
def dfs(current_node: TrieNode, current_word: str) -> None:
if current_node.is_end:
results.append(current_word)
for char, child in current_node.children.items():
dfs(child, current_word + char)
dfs(node, prefix)
return sorted(results)
# Demo
trie = Trie()
for word in ["cat", "car", "card", "care", "bat", "bad"]:
trie.insert(word)
print(trie.search("car")) # True
print(trie.search("ca")) # False: 'ca' is a prefix but not a complete word
print(trie.starts_with("ca")) # True
print(trie.autocomplete("ca")) # ['car', 'card', 'care', 'cat']
print(trie.autocomplete("ba")) # ['bad', 'bat']`search('ca')` returns False but `starts_with('ca')` returns True. Both call `_traverse` and both find a node. What separates them?
#Expression Trees: The Canonical Postorder Use Case
+, -, *, /). Postorder evaluates it naturally: finish both subtrees (the operands) first, then apply the operator.Expression Tree: (3 + 4) * (5 - 2)
3 + 4 = 7. Visit 5 and 2, then compute 5 - 2 = 3. Finally apply *: 7 * 3 = 21.from typing import Optional
class ExprNode:
def __init__(self, value: str) -> None:
self.value = value
self.left: Optional[ExprNode] = None
self.right: Optional[ExprNode] = None
def evaluate(node: Optional[ExprNode]) -> float:
"""Evaluate an expression tree using postorder. O(n)."""
if node is None:
return 0.0
# Leaf node: it is a number
if node.left is None and node.right is None:
return float(node.value)
left_val = evaluate(node.left)
right_val = evaluate(node.right)
ops = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"*": lambda a, b: a * b,
"/": lambda a, b: a / b,
}
if node.value not in ops:
raise ValueError(f"Unknown operator: {node.value}")
return ops[node.value](left_val, right_val)
# Build (3 + 4) * (5 - 2) manually
root = ExprNode("*")
root.left = ExprNode("+")
root.right = ExprNode("-")
root.left.left = ExprNode("3")
root.left.right = ExprNode("4")
root.right.left = ExprNode("5")
root.right.right = ExprNode("2")
print(evaluate(root)) # 21.0evaluate recurses into both children BEFORE looking at node.value. What breaks if you apply the operator first and recurse afterwards?
#Key Takeaways
- BST delete has exactly three cases: leaf (just remove), one child (replace with the child), two children (copy in the inorder successor's value, then delete the successor)
is_valid_bstneeds bounds passed down: checking only a node against its direct children silently accepts invalid trees, and this is one of the most common BST mistakes- Self-balancing trees (AVL, Red-Black) keep the height near log n by rotating. In everyday Python, use
sortedcontainers.SortedListrather than writing rotations yourself - Tries find words by prefix in O(L), however many words are stored. Hash maps cannot do this well because words with the same start are not stored together
- Postorder evaluates expression trees naturally. Both operands (the children) must be computed before the operator (the parent) can be applied. The same reason makes postorder right for deleting a tree
The delete operation for a BST node with TWO children uses the 'inorder successor'. Why not use the predecessor (largest value in the left subtree) instead?