Binary Trees & Traversals
Vocabulary
- Node: holds a value and links to its children.
- Root: the top node. Leaf: a node with no children.
- Binary tree: each node has at most 2 children (left and right).
- Height: the longest path from the root to a leaf.
Traversals (ways to visit every node)
| Order | Visit | Use |
|---|---|---|
| Pre-order | node → left → right | copying or serialising a tree |
| In-order | left → node → right | sorted output from a BST |
| Post-order | left → right → node | deleting, computing sizes |
| Level-order (BFS) | row by row, with a queue | shortest depth, printing levels |
All are O(n).
The recursive mindset
Most tree problems look like this:
def solve(node):
if node is None:
return BASE
left = solve(node.left)
right = solve(node.right)
return combine(node.val, left, right)
Examples: height, size, sum, maximum, "is it balanced?", "are two trees equal?".
Space
Recursion uses O(h) stack space, where h is the height: O(log n) for a balanced tree, O(n) for a tree that looks like a line.
Example
from collections import deque
class Node:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
# 1
# / \
# 2 3
# / \ \
# 4 5 6
root = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))
def preorder(n): return [] if not n else [n.val] + preorder(n.left) + preorder(n.right)
def inorder(n): return [] if not n else inorder(n.left) + [n.val] + inorder(n.right)
def postorder(n): return [] if not n else postorder(n.left) + postorder(n.right) + [n.val]
def height(n):
return 0 if not n else 1 + max(height(n.left), height(n.right))
def level_order(root):
levels, q = [], deque([root])
while q:
levels.append([n.val for n in q])
q = deque(c for n in q for c in (n.left, n.right) if c)
return levels
print(preorder(root)) # [1, 2, 4, 5, 3, 6]
print(inorder(root)) # [4, 2, 5, 1, 3, 6]
print(postorder(root)) # [4, 5, 2, 6, 3, 1]
print(height(root)) # 3
print(level_order(root)) # [[1], [2, 3], [4, 5, 6]]