Data Structures and Algorithms5 min read

Tree Traversals in Interviews: Level-Order BFS, Recursive DFS, and LCA

How to choose between iterative level-order BFS and bottom-up recursive DFS on binary trees, why Lowest Common Ancestor simplifies in BSTs versus general binary trees, and common recursion bugs.

Level-order BFS groups tree nodes by depth using a deque and a snapshotted level size loop, while post-order DFS solves subtree properties by returning clean state upward from left and right children. In Lowest Common Ancestor queries, general binary trees return matching nodes upward in O(n), whereas Binary Search Trees use value comparisons to walk straight down in O(h).

Key takeaways

  • Use BFS when distance from root or horizontal right-side views define the answer.
  • Define a clear recursive return contract on None before writing DFS body code.
  • Verify whether tree values obey BST ordering before scanning both subtrees unnecessarily.

Quick facts

  • Snapshotting len(q) before each BFS inner loop isolates one depth layer without mixing child levels.
  • Post-order DFS computes left and right answers before deciding at the parent node.
  • Binary tree LCA returns the split node where both left and right subtrees return non-null values.
  • BST LCA cuts search space to one branch at each step using O(1) iterative space.

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.

Comparison of BFS level-order queue snapshot and DFS post-order subtree return contract
Comparison of BFS level-order queue snapshot and DFS post-order subtree return contract

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 O(n)O(n) traversal into an O(n2)O(n^2) 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:

  1. If node is None, node is p, or node is q, return node immediately.
  2. Recurse on left = lca(node.left, p, q) and right = lca(node.right, p, q).
  3. If both left and right are non-null, p and q live in opposite branches, so node is their split ancestor.
  4. Otherwise return left if left is not None else right.
Bottom-up LCA return trace for p=5 and q=4 in a binary tree
Bottom-up LCA return trace for p=5 and q=4 in a binary tree

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 O(log⁡n)O(\log n) or O(1)O(1).

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 O(1)O(1) extra space.

Working Python Implementations

Here is a unified module defining TreeNode, level_order, lowest_common_ancestor, and lca_bst, tested on concrete trees.

PYTHON
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:

TEXT
level_order: [[3], [5, 1], [6, 2, 8], [4]]
lca(5, 4): 5
bst_lca(2, 8): 6

Complexity Analysis

Traversal / OperationTime ComplexityExtra Space (Worst)Extra Space (Balanced)
Level-order BFSO(n)O(n)O(n)O(n) (widest leaf layer)O(n)O(n)
Binary Tree LCA (DFS)O(n)O(n)O(n)O(n) (skewed chain)O(log⁡n)O(\log n)
BST LCA (iterative)O(h)O(h)O(1)O(1)O(1)O(1)

Note the space contrast: BFS space scales with maximum tree width (up to n/2n/2 nodes on the bottom level of a complete binary tree), whereas DFS recursion space scales with tree height hh.

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 p early on encounter falsely reports p even when q is missing. In that variant, traverse the full tree and track boolean flags found_p and found_q.
  • Comparing node values in duplicate-value trees: Using root.val == p.val instead of object identity (root is p) breaks when distinct nodes share integers.
  • Forgetting `if root is None:` before `deque([root])`: Passing None into the initial queue triggers AttributeError on node.val.
  • Mixing BST and general binary tree assumptions: Applying lca_bst logic to an unordered binary tree fails silently on unsorted children.

I skip recursive DFS when input height can reach 10510^5 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:

  1. Binary Tree Level Order Traversal: Implement deque level isolation and test skewed and empty root edge cases.
  2. Lowest Common Ancestor of a Binary Tree: Implement the single-pass split check and follow up with the iterative BST variant.

Sources