Deciding Between Level-Order BFS and Recursive DFS
Trees sit at the center of coding interviews because they turn abstract recursion into concrete pointer relationships. Before writing a single helper function, I decide between breadth-first search and depth-first search by asking one question: does the problem group nodes by horizontal depth or combine results from subtrees?
If the answer depends on shallowest distance, zigzag layers, or rightmost node per row, level-order BFS with `collections.deque` is the natural fit. If the answer depends on subtree height, diameter, validation, or ancestor relationships, recursive DFS wins because each stack frame aggregates left and right children naturally.
Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).
Intuition and Traversal Contracts
1. Level-order BFS with a frozen queue snapshot
Beginners often struggle to separate tree levels inside a while queue: loop. The trick is freezing the current layer size with level_size = len(q) at the top of each outer iteration.
Because newly appended children land at the back of q after level_size items, popping exactly level_size elements processes one complete horizontal band while staging the next band cleanly behind it. Notice that trees have no back edges, so unlike general graphs, tree BFS needs no visited set.
2. Bottom-up DFS and Lowest Common Ancestor
Recursive DFS shines when you specify the return contract first. As the CP-Algorithms DFS summary notes, trees guarantee a single simple path between any two vertices, which makes subtree properties well-defined.
Before writing recursion, I separate top-down (pre-order) state from bottom-up (post-order) state. In top-down problems like counting "good nodes" greater than every ancestor or validating BST [low, high] ranges, you pass constraints downward as function arguments (dfs(node, low, high)). In bottom-up problems like tree height, balance checks, diameter, and Lowest Common Ancestor (LCA), children compute partial summaries first and return values upward to the parent.
Whenever you compute two metrics simultaneously in one post-order pass (such as diameter or max path sum), avoid calling a separate height(node) helper at every node, which turns an traversal into an quadratic cascade on skewed trees. Instead, update a single best accumulator while returning the branch contribution (1 + max(left_h, right_h)).
Consider Lowest Common Ancestor (LCA) for two nodes p and q guaranteed to exist in the tree. At any node:
- If
node is None,node is p, ornode is q, returnnodeimmediately. - Recurse on
left = lca(node.left, p, q)andright = lca(node.right, p, q). - If both
leftandrightare non-null,pandqlive in opposite branches, sonodeis their split ancestor. - Otherwise return
left if left is not None else right.
Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).
Why does returning node early when node is p work even if q sits inside p's own subtree? Because in that case, p itself is the LCA, and the opposite side of the higher split returns None, allowing p to bubble cleanly to the root. Note that if you need to answer thousands of LCA queries offline or online on a fixed tree, preprocessing an Euler tour or binary lifting table as described in CP-Algorithms LCA drops query latency to or .
When the input is a Binary Search Tree (BST), you do not recurse into both branches at all. Walk down iteratively: if both values are smaller than curr.val, step left; if both are larger, step right; the first node between them (or equal to one of them) is the LCA in extra space.
Working Python Implementations
Here is a unified module defining TreeNode, level_order, lowest_common_ancestor, and lca_bst, tested on concrete trees.
from __future__ import annotations
from collections import deque
class TreeNode:
def __init__(
self,
val: int,
left: TreeNode | None = None,
right: TreeNode | None = None,
) -> None:
self.val = val
self.left = left
self.right = right
def level_order(root: TreeNode | None) -> list[list[int]]:
if root is None:
return []
q: deque[TreeNode] = deque([root])
levels: list[list[int]] = []
while q:
band: list[int] = []
for _ in range(len(q)):
node = q.popleft()
band.append(node.val)
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
levels.append(band)
return levels
def lowest_common_ancestor(
root: TreeNode | None, p: TreeNode, q: TreeNode
) -> TreeNode | None:
if root is None or root is p or root is q:
return root
left = lowest_common_ancestor(root.left, p, q)
right = lowest_common_ancestor(root.right, p, q)
if left is not None and right is not None:
return root
return left if left is not None else right
def lca_bst(root: TreeNode | None, p_val: int, q_val: int) -> TreeNode | None:
curr = root
lo, hi = min(p_val, q_val), max(p_val, q_val)
while curr is not None:
if hi < curr.val:
curr = curr.left
elif lo > curr.val:
curr = curr.right
else:
return curr
return None
if __name__ == "__main__":
n6, n4 = TreeNode(6), TreeNode(4)
n2 = TreeNode(2, right=n4)
n5 = TreeNode(5, left=n6, right=n2)
n8 = TreeNode(8)
n1 = TreeNode(1, right=n8)
root = TreeNode(3, left=n5, right=n1)
assert level_order(root) == [[3], [5, 1], [6, 2, 8], [4]]
ans = lowest_common_ancestor(root, n5, n4)
assert ans is n5
bst = TreeNode(6, TreeNode(2, TreeNode(0), TreeNode(4)), TreeNode(8))
bst_ans = lca_bst(bst, 2, 8)
assert bst_ans is bst
print("level_order:", level_order(root))
print("lca(5, 4):", ans.val if ans else None)
print("bst_lca(2, 8):", bst_ans.val if bst_ans else None)Running this script outputs:
level_order: [[3], [5, 1], [6, 2, 8], [4]]
lca(5, 4): 5
bst_lca(2, 8): 6Complexity Analysis
| Traversal / Operation | Time Complexity | Extra Space (Worst) | Extra Space (Balanced) |
|---|---|---|---|
| Level-order BFS | (widest leaf layer) | ||
| Binary Tree LCA (DFS) | (skewed chain) | ||
| BST LCA (iterative) |
Note the space contrast: BFS space scales with maximum tree width (up to nodes on the bottom level of a complete binary tree), whereas DFS recursion space scales with tree height .
Common Mistakes and When I Skip Recursive DFS
Four traps repeatedly surface on tree problems:
- Assuming `p` and `q` always exist in the tree: If one target might be absent, returning
pearly on encounter falsely reportspeven whenqis missing. In that variant, traverse the full tree and track boolean flagsfound_pandfound_q. - Comparing node values in duplicate-value trees: Using
root.val == p.valinstead of object identity (root is p) breaks when distinct nodes share integers. - Forgetting `if root is None:` before `deque([root])`: Passing
Noneinto the initial queue triggersAttributeErroronnode.val. - Mixing BST and general binary tree assumptions: Applying
lca_bstlogic to an unordered binary tree fails silently on unsorted children.
I skip recursive DFS when input height can reach skewed nodes in Python (where default recursion limit 1000 raises RecursionError unless converted to an explicit stack or iterative BFS), or when the problem asks strictly for shortest depth or horizontal layer slices.
Practice Problems
Solidify both queue snapshots and subtree return logic on these two problems:
- Binary Tree Level Order Traversal: Implement
dequelevel isolation and test skewed and empty root edge cases. - Lowest Common Ancestor of a Binary Tree: Implement the single-pass split check and follow up with the iterative BST variant.
