Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Trees/Tree DFS (Paths & Recursion)

Learn the pattern · ~15 min

Tree DFS (Paths & Recursion)

also called post-order aggregation, top-down state

Let every node ask its children, combine their answers, and return one summary to its parent; record anything the parent can't extend, like a bent path, on the side.

Signalsheight, diameter, balance, path sumslowest common ancestorvalue computed from children
Cheat sheet and practice

Reach for it when you read

  • +The answer for a node depends on what its subtrees report: height, size, balanced or not, "is p in there?".
  • +A root-to-leaf path condition: a target sum, the biggest value seen so far, the path itself.
  • +The best path may bend through any node (diameter, max path sum): return one arm, track the bend.
  • +A choice per node that depends on its children's choices (rob it or not, put a camera or not): return a pair.
  • +Your brute force recomputes a subtree's height or sum once per ancestor.

Not this one when

  • ×The answer is per level or the nearest leaf: tree BFS.
  • ×The tree is a BST and the question is about sorted order: an in-order walk, or compare and branch.
  • ×Many ancestor or LCA queries on one fixed tree: binary lifting, not one DFS per query.

Learn Tree DFS (Paths & Recursion)

First, what do "DFS", "depth" and "height" mean?

DFS stands for depth-first search: go all the way down one branch before coming back for the next. In a tree, a function calls itself on the left child, then the right. Two words get mixed up; pin them on this tree:

Text
      1
     /
    2
   / \
  3   4
 /     \
5       6
  • The depth of a node counts the edges from the root down to it. Node 1 has depth 0, node 2 depth 1, nodes 5 and 6 depth 3.
  • The height of a node counts the nodes on the longest way from it down to a leaf. Node 5 has height 1 (just itself), node 3 has height 2, node 1 has height 4.

Depth is about the path above a node; height about the subtree below it. That difference is the whole pattern.

How does one walk carry both?

The rule:

A fact about the path above goes down as a parameter. A fact about the subtree below comes up as a return value.

The parent hands each child depth + 1; the child hands back its height:

step what happens call stack (root → current)
1 start at 1 with depth 0 1
2 1 calls its left child 2 with depth 1 1, 2
3 2 calls 3 with depth 2 1, 2, 3
4 3 calls 5 with depth 3 1, 2, 3, 5
5 both of 5's children are null and return 0, so 5 returns height 1 1, 2, 3
6 3's right child is null (0): 3 returns 1 + max(1, 0) = 2 1, 2
7 2 calls 4 with depth 2 1, 2, 4
8 4's left is null; it calls 6 with depth 3 1, 2, 4, 6
9 6 is a leaf: returns 1 1, 2, 4
10 4 returns 1 + max(0, 1) = 2 1, 2
11 2 returns 1 + max(2, 2) = 3 1
12 1's right is null: returns 1 + max(3, 0) = 4 empty

A node's depth is known when it is called; its height only when it returns. The stack only ever holds one root-to-node path.

The code for it

C++
int dfs(TreeNode* node, int depth) {        // depth comes down from the parent
    if (!node) return 0;                    // an empty tree has height 0
    int L = dfs(node->left, depth + 1);
    int R = dfs(node->right, depth + 1);
    int height = 1 + max(L, R);             // height goes back up
    cout << node->val << ": depth " << depth << ", height " << height << '\n';
    return height;
}

It prints 5, 3, 6, 4, 2, 1, each node after both its children (post-order), with the table's depths and heights. You don't need to memorise this: go down with depth + 1, come back up with 1 + max(L, R).

Why does a null child return 0? Then a leaf gets 1 + max(0, 0) = 1 with no special case.

Fine, but how does this help us?

Here's a classic problem: the diameter of a binary tree, the number of edges on the longest path between any two nodes. The path may go up and come back down, and needn't pass through the root. Its ends are leaves or the root, so try those pairs by hand:

ends path edges
5 and 6 5 → 3 → 2 → 4 → 6 4
5 and 1 5 → 3 → 2 → 1 3
6 and 1 6 → 4 → 2 → 1 3

The answer is 4, and that path skips the root.

The brute force

Every path has one highest node where it bends. The longest path bending at a node goes as far down each side as it can: the left child's height plus the right child's. Try every node:

C++
int height(TreeNode* node) {
    if (!node) return 0;
    return 1 + max(height(node->left), height(node->right));
}
int diameterBrute(TreeNode* node) {
    if (!node) return 0;
    int here = height(node->left) + height(node->right);   // the path bending at node
    return max({here, diameterBrute(node->left), diameterBrute(node->right)});
}

It returns 4. But height walks a whole subtree, at every node. On a chain, node k walks the n − k nodes below it: about n²/2 visits. LeetCode allows only 10⁴ nodes, so it passes there (5 × 10⁷ visits, 0.3 s with -O2). At n = 10⁵ it's 5 × 10⁹ visits and 30 seconds: time limit exceeded.

The one thought that fixes it

Stop at node 2. At node 1 the brute force already asked for height(2), walking 2, 3, 5, 4 and 6. Now it asks for height(3) and height(4), walking 3, 5, 4 and 6 again. But height(2) is just 1 + max(2, 2) = 3, built from those two numbers. One walk was enough.

So compute heights once, bottom up, as the walk in the table did. While a node holds both children's heights, the path bending there is L + R: record it in best. But a path can't fork, so the parent can extend only one arm: return 1 + max(L, R).

C++
int best = 0;
int arm(TreeNode* node) {
    if (!node) return 0;
    int L = arm(node->left);
    int R = arm(node->right);
    best = max(best, L + R);                // the path that bends here
    return 1 + max(L, R);                   // the parent can extend one arm only
}
int diameterOfBinaryTree(TreeNode* root) { best = 0; arm(root); return best; }

Dry run

Same tree. The children's heights L and R are also the arm lengths in edges:

node L R L + R (bends here) returns best
5 0 0 0 1 0
3 1 0 1 2 1
6 0 0 0 1 1
4 0 1 1 2 1
2 2 2 4 3 4
1 3 0 3 4 4

The answer is 4, the same answer as the brute force.

Why it's O(n)

Count what happens to each node: it is called once and does O(1) work after its children report: O(n) time. Space is the call stack, one root-to-node path: O(h), n on a chain, about log n when balanced.

From O(n²) to O(n): each child hands its height up instead of being measured again.

Path Sum? Carry what's left down

Does some root-to-leaf path add up to a target? That's about the path above, so pass down the sum still needed.

C++
bool hasPathSum(TreeNode* node, int need) {
    if (!node) return false;
    need -= node->val;                                  // what's left after this node
    if (!node->left && !node->right) return need == 0;  // only a leaf ends a path
    return hasPathSum(node->left, need) || hasPathSum(node->right, need);
}

Target 13 → true (1 + 2 + 4 + 6). Target 11 → true (1 + 2 + 3 + 5). Target 6 → false: 1 + 2 + 3 is 6, but 3 isn't a leaf.

Longest ZigZag? Carry two counts down

A zigzag path goes down, switching between left and right at every step. Only the path's last step matters, so pass two counts down: the zigzag ending here by a left step, and by a right step.

C++
int zz = 0;                                   // the longest so far; start with zigzag(root, 0, 0)
void zigzag(TreeNode* node, int L, int R) {   // zigzags ending here by a left / right step
    if (!node) return;
    zz = max({zz, L, R});
    zigzag(node->left, R + 1, 0);             // a left step extends one that came by a right step
    zigzag(node->right, 0, L + 1);
}
node arrived with (L, R) why
2 (1, 0) a left step after nothing
3 (1, 0) a left step after a left step starts over
4 (0, 2) a right step after 2's left step: 1 → 2 → 4
6 (0, 1) right after right: starts over

The longest zigzag is 2 edges. Going the same way twice restarts the count at 1, not 0: the step you just took still counts.

Remember this

  • Facts about the path above (depth, sum so far, the last step) go down as parameters. Facts about the subtree below (height, count, "found it") come up as return values.
  • If the answer can bend through a node, return one arm and record the bend outside.
  • An empty child returns 0 (or false, or null), so leaves need no special case, unless the rule is about leaves, like Path Sum's.
  • Whenever a tree problem talks about paths, heights, or what each subtree reports, it's tree DFS.

Practise it on Maximum Depth of Binary Tree, then Path Sum (state down), Diameter of Binary Tree (return one, record another), Count Good Nodes in Binary Tree (the biggest value so far goes down), Lowest Common Ancestor of a Binary Tree (return a node) and Binary Tree Maximum Path Sum (the diameter's shape with values; clamp negative arms at 0).

Below, watch Diameter of Binary Tree run line by line.

Watch it work, line by line

Diameter of Binary Tree ↗, root = [1, 2, 3, 4, 5, null, null, 6] → 4 (6-4-2-1-3). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 4 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Can each node's answer be built from its children's answers, or from what its ancestors pass down, visiting every node once?

Reach for it when

  • +height, diameter, balance, path sums
  • +lowest common ancestor
  • +value computed from children
  • +n up to 1e5 (watch recursion depth)

It fails when

  • ×Strict level-by-level outputuse Tree BFS
  • ×Shortest path by edge countuse BFS, stops without exploring the whole tree
  • ×Multiple interacting choices per node (take/skip, colourings)use Tree DP
  • ×Answer needed for every node as rootuse Rerooting
  • ×Many path queriesuse Binary lifting or HLD

Looks like it, isn't (and the other way round)

  • Minimum Height Trees looks like Tree DFS (Paths & Recursion), needs Topological Sort

    Trying every root is O(n2); peeling leaves (Kahn on degree 1) finds centres.

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1In the diameter, why return 1 + max(L, R) and not L + R?Reveal

    The parent can extend only one arm. A path that bends at a node can't continue upward, so the bend is recorded in best instead.

  • 2What should an empty subtree return for heights or sums?Reveal

    The identity: 0. For max path sum, also clamp a negative arm at 0 so it's never used.

  • 3"Is there a root-to-leaf path summing to 22?" Top-down or bottom-up?Reveal

    Top-down: pass the remaining sum down and check it at each leaf.

Practice ladder

every problem →
  1. 1Maximum Depth of Binary Treereturn upEasy
  2. 2Path Sumstate carried downEasy
  3. 3Diameter of Binary Treethe hookEasy
  4. 4Path Sum IIthe path as stateMedium
  5. 5Count Good Nodes in Binary Treestate carried downMedium
  6. 6Lowest Common Ancestor of a Binary Treereturn a nodeMedium
  7. 7House Robber IIIreturn a pairMedium
  8. 8Binary Tree Maximum Path Sumreturn one, track anotherHard

Finished Tree DFS (Paths & Recursion)? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Tree DFS (Paths & Recursion)

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial