DEV Community

Cover image for Binary Tree Interview Problems: 6 Traversal Patterns, 15 Problems
Prakhar Srivastava for codeintuition

Posted on • Originally published at codeintuition.io

Binary Tree Interview Problems: 6 Traversal Patterns, 15 Problems

The default tree prep is sorting LeetCode's tree tag by acceptance rate, doing the top 40, and hoping the patterns transfer. They mostly don't. Tree problems feel unpredictable because the practice was organised by popularity, not by mechanism. Every binary tree interview problem is moving information through the tree in one of six ways, and once the six are visible, fifteen problems give more coverage than forty random ones.

TL;DR: Binary tree interview problems cluster around six traversal patterns: preorder, postorder, root to leaf, level order, lowest common ancestor, and simultaneous traversal. Two problems per pattern is enough for interview-grade coverage. The trick is to practice in pattern order, not difficulty order.

The six patterns that cover the binary tree interview space

Every tree problem is a question about how information has to move. Preorder pushes information down from parent to child. Postorder pushes it up from child to parent. Root to leaf accumulates state along a single path. Level order processes nodes layer by layer with a queue. Lowest common ancestor is about which subtrees contain which targets. Simultaneous traversal walks two trees in parallel to compare or merge structure.

  • Preorder. Information flows down. Pass current state into the recursive call.
  • Postorder. Information flows up. Compute the answer from what the children return.
  • Root to leaf. State accumulates along a path. Backtrack after each child.
  • Level order. Use a queue. Process all nodes at depth d before any at depth d+1.
  • Lowest common ancestor. Recursive search. Return a target on the way back up.
  • Simultaneous traversal. Two trees, one walk. Compare or merge at every step.

Two problems per pattern is the right calibration. The first problem teaches the mechanism. The second forces a variation that reveals whether the mechanism transferred or got memorised. Past two, the marginal practice value drops fast, because the third problem in a pattern usually just rehearses what the second one already established.

Stateful postorder, where the medium and hard problems live

Most of the medium and hard binary tree problems are stateful postorder. The recursion returns something the parent needs (usually height), but the answer lives in a variable updated at each node. That split between "what the function returns" and "what you care about" is what makes the pattern hard to grasp from one problem alone.

Diameter is the cleanest place to see it. The diameter of a binary tree is the longest path between any two nodes, measured in edges. The path can pass through the root or be entirely inside a subtree. The recursion has to return the height of each subtree (so the parent can compute its own height), but the answer (longest path) is computed at each node as left_height + right_height and tracked separately.

def diameter(root):
    longest = 0

    def height(node):
        nonlocal longest
        if node is None:
            return 0
        left_h = height(node.left)
        right_h = height(node.right)
        longest = max(longest, left_h + right_h)
        return 1 + max(left_h, right_h)

    height(root)
    return longest
Enter fullscreen mode Exit fullscreen mode

Two things to notice. First, the function is named height, not diameter. That naming is deliberate. The recursion is computing height, and diameter falls out as a side effect at each node. Second, longest is a nonlocal variable, which is the Python way to track an answer outside the recursive frame. In other languages you'd use an instance variable or a single-element list. The mechanism is the same.

Once the diameter mechanism clicks, half a dozen other problems unlock with no extra learning. Distribute coins tracks surplus or deficit at each subtree while a global counter tracks total moves. Longest monotonic path tracks the longest increasing and decreasing chain at each node while a global tracks the overall longest. Maximum path sum tracks the best downward path from each node while a global tracks the best path that bends through any node. Same skeleton, different state.

The diameter lesson walks the recursion variable by variable, which is the depth that makes the "function returns one thing, answer lives elsewhere" framing stick. The framing is what transfers, not the specific problem.

The 15 problems, grouped by pattern

The list below is what comes out when you group binary tree interview problems by mechanism instead of by popularity or difficulty. Two problems per pattern. The first is the direct application, the second is the variant that proves the mechanism transferred.

Preorder (information flows down):

  • Sum of path. Stateless preorder. Pass the remaining target sum down, check for zero at a leaf.
  • Right view. Stateful preorder. Pass depth down, track the deepest depth seen so far globally.

Postorder (information flows up):

Root to leaf (state accumulates along a path):

  • Root to leaf paths. Enumerate every path. Backtrack after each recursive call.
  • Equal paths. Check whether any path sums to a target. Validate only at leaves.

Level order (queue, layer by layer):

Lowest common ancestor (multi node reasoning):

Simultaneous traversal (two trees, one walk):

Three additional postorder problems (distribute coins, longest monotonic path, maximum path sum) sit alongside diameter as variants of the same stateful skeleton. Adding any of them to your list gives diminishing returns once diameter is solid, which is why the 15-problem cut works.

Why pattern order beats difficulty order

The conventional advice is to do easy problems first, then mediums, then hards. For binary tree interview problems specifically, that ordering is wrong. A medium postorder problem can be easier than a hard preorder problem if you already understand preorder and haven't met postorder yet. The skill that transfers is the pattern mechanism, not the difficulty class.

Pattern order looks like this:

  1. Preorder before postorder, because preorder is what most people already do intuitively when they imagine walking a tree.
  2. Postorder before root to leaf, because root to leaf borrows the return mechanism from postorder.
  3. Root to leaf before level order, because level order is a different paradigm (queue based) and benefits from the recursive patterns being solid first.
  4. Level order before LCA, because LCA is multi node reasoning and the single-walk patterns have to feel automatic first.
  5. LCA before simultaneous traversal, because simultaneous traversal scales LCA-style reasoning to two trees instead of two nodes.

Within each pattern, do the direct application first and the variant second. Height before diameter. LCA before distance between nodes. Identical trees before subtree detection. If you can't trace the solution to the direct application on paper without running the code, the variant won't transfer either.

Three recursion mistakes that derail tree rounds

These come up across most tree rounds I see, in roughly this order under interview pressure.

  • Returning the answer when the parent needs supporting information. The "what does the recursion return?" question is the one most candidates get wrong on stateful problems. In longest monotonic path, the function needs to return the longest increasing and decreasing chains so the parent can extend them. The actual answer (longest path overall) gets updated at each node by combining left and right chains. If you try to return the answer directly, the parent can't use it to extend its own chain.
  • Missing the backtrack in path enumeration. Root to leaf paths shares a path list across recursive calls. If you don't remove the last element after each child returns, earlier paths bleed into later ones. The output looks almost right, which is what makes the bug expensive to diagnose mid-interview.
  • Wrong base case for the problem. if not node: return 0 is correct for height because the height of a null subtree is zero. It is wrong for equal paths, where you need to distinguish between "node is null" and "node is a leaf." Returning at null makes you incorrectly treat the null children of single-child nodes as valid leaves. The fix is to add an explicit leaf check before the null check, or to handle the null case as "no path here, ignore" rather than "valid empty path."

The pattern in all three is the same. The mechanism is right, but the boundary handling is wrong, and the failure mode is "passes most test cases, breaks on the edge case the interviewer planted on purpose."

The 6-pattern framing is the thing I keep coming back to in how I think about tree prep on Codeintuition, because grouping by mechanism is what turns 15 problems into 15 instances of recognisable techniques instead of 15 stand-alone puzzles. Most tree practice I see does the opposite: 40 problems, none of them grouped, and the candidate ends up freezing on the next unfamiliar one anyway.

I wrote a longer version on my own blog that walks each pattern through its two problems and includes the recursion-bug catalogue with worked examples.

Which tree pattern did the most for you, where one or two problems unlocked a dozen variations you didn't have to memorise?

Top comments (0)