Binary trees and BSTs
Most tree problems are one traversal: a DFS where each node combines what its children return, or a BFS level by level; in a BST, inorder visits the keys in sorted order.
Analogy: An org chart: each manager asks their two reports for a number, combines the answers and passes one number up to their own boss.
How it works
- DFS by recursion: preorder handles the node first, inorder between its children, postorder after both.
- BFS with a queue goes level by level; read the queue length to isolate each level.
- Return info up: a node reports its height while tracking the best diameter seen.
- BST:
left subtree < node < right subtreeat every node, so inorder is sorted. - LCA: the node where the two targets come back from different subtrees.
Check yourself
Answer to mark it learned; your answers aren't scored.
A service needs the lowest common ancestor of two keys in a balanced BST with 10⁶ nodes, on every request. Which approach?
Go deeper
Solve it in Python 10
- Depth of the deepest leafeasy
- Mirror a binary treeeasy
- Closest shared ancestormedium
- Downward paths adding to a targetmedium
- Is it a search tree?medium
- Every node k steps awaymedium
- Rebuild a tree from its traversalsmedium
- Rightmost value on each levelmedium
- Heaviest path in a treehard
- Tree to text and backhard
Full explanation
A binary tree node has a value and up to two children. Almost every problem is one O(n) traversal:
- DFS (recursion): preorder handles the node before its children (copy, serialize), inorder between them, postorder after both, when the node needs its children's answers.
- BFS (queue): level by level; read the queue length first to process exactly one level. It is Graph traversal: BFS and DFS without a visited set.
Return information up: each call returns what its parent needs. For the diameter, the best path through a node is left height + right height, but the node returns 1 + max(left, right), because a parent can extend only one side.
A binary search tree (BST) keeps left subtree < node < right subtree at every node. So inorder yields the keys sorted, and search costs O(height), like Binary search and search on the answer.
Lowest common ancestor (LCA): recurse into both sides; the node where p and q come back from different sides is the answer. In a BST, walk down from the root until the two values split.
Code Diameter, level order, validate BST and LCA
from collections import deque
def diameter(root) -> int: # longest path between two nodes, in edges
def walk(node): # returns (height, best diameter) of the subtree
if not node:
return 0, 0
(lh, lb), (rh, rb) = walk(node.left), walk(node.right)
return 1 + max(lh, rh), max(lb, rb, lh + rh) # a parent extends ONE side
return walk(root)[1]
def level_order(root) -> list[list[int]]:
levels, q = [], deque([root] if root else [])
while q:
levels.append([n.val for n in q]) # the queue holds one full level
for _ in range(len(q)): # snapshot: only this level
n = q.popleft()
q.extend(c for c in (n.left, n.right) if c)
return levels
def is_bst(node, lo=float("-inf"), hi=float("inf")) -> bool:
if not node:
return True
ok = lo < node.val < hi # bounds come from ALL ancestors, not the parent
return ok and is_bst(node.left, lo, node.val) and is_bst(node.right, node.val, hi)
def lca(root, p, q):
if root is None or root is p or root is q:
return root
left, right = lca(root.left, p, q), lca(root.right, p, q)
return root if left and right else left or right # both sides found: split pointReal example
Take the tree in the diagram: 8 with children 3 and 10; below them 1, 6 and 9, 14.
Diameter: each leaf returns height 1; nodes 3 and 10 return 2 and each sees a path of 1 + 1 = 2 edges; the root sees 2 + 2 = 4 (1→3→8→10→14). One postorder pass visits each of the 7 nodes once.
Validate BST: hang a 12 as the right child of 6. It passes the parent check (12 > 6) but sits in the left subtree of 8, so the bound < 8 rejects it.
Trade-offs +3 · −3
+ You gain
- One O(n) traversal solves most problems; the recursion mirrors the structure.
- A balanced BST gives O(log n) search, insert and delete, plus sorted iteration and range queries.
- The "return info up" template covers height, diameter, balance, path sums and LCA.
− You pay
- Recursion depth equals the tree height: a skewed tree of 10⁵ nodes exceeds Python's default recursion limit.
- A plain BST degrades to O(n) per operation when keys arrive in sorted order.
- Easy to confuse what a call returns to its parent with the answer it records.
Use it when
The input is a tree or hierarchy (file system, DOM, org chart, expression): DFS for per-subtree answers and paths, BFS for levels and nearest nodes, a BST when you need ordered keys with fast updates.
Avoid it when
Graphs with cycles or shared children need a visited set (Graph traversal: BFS and DFS). For plain key lookup with no ordering, a hash map is O(1). Don't hand-roll a balanced BST unless asked.
Numbers to know 5
- Traversal: O(n) time. Space: O(h) for DFS (h = height), O(w) for BFS (w = widest level, up to ~n/2).
- Height: ~log₂ n when balanced (~20 for 10⁶ nodes), n when skewed like a linked list.
- BST search, insert, delete: O(h), so O(log n) balanced and O(n) skewed.
- A perfect tree with L levels has 2ᴸ − 1 nodes; the last level holds 2ᴸ⁻¹, about half.
- CPython's default recursion limit is 1,000 frames.
Common pitfalls 4
- Validating a BST by comparing each node only with its children: the bounds come from all its ancestors.
- Diameter: returning
lh + rhto the parent instead of1 + max(lh, rh). A path can't fork twice. - Calling
height()inside every recursive call: O(n²) on a skewed tree. Compute it once, bottom-up. - Level order without reading the queue length first: levels bleed into each other.
Interview questions 3
Answer out loud first, then reveal.
How do you approach a binary tree problem?Show answer
I ask what one call should return to its parent. If a node's answer depends on its subtrees (height, diameter, balanced, path sum), it's a postorder DFS that returns that fact and tracks the best answer. If information flows down, like the bounds in a BST check, I pass it as arguments. If the question says levels, depth or nearest, it's BFS. Then I state O(n) time, O(h) space, and the stack risk on a skewed tree.
Find the lowest common ancestor of two nodes. And if the tree is a BST?Show answer
General tree: recurse left and right. A call returns the node itself if it is p or q, otherwise whatever its children found. The first node that gets a non-null result from both sides is the LCA: O(n) time, O(h) stack. In a BST I use the ordering instead: from the root, go left if both values are smaller, right if both are larger, and stop where they split. That is O(h), no recursion.
Why is a plain BST risky in production, and what do you use instead?Show answer
Its cost is O(height), and inserting sorted keys makes the height n: every operation becomes a list scan. Production code uses self-balancing trees, such as the red-black tree behind Java's TreeMap, or B-trees on disk (Database indexes: B-tree vs LSM), which keep the height O(log n). Python has no built-in balanced BST: for small data I'd keep a sorted list with bisect, accepting O(n) inserts.