What should a recursive call return?
1 The boss's question is not always the one to pass down
In the tree basics lesson, the CEO wanted the size of the company. She asked each report "how many people are in your team?" and added the answers. Every manager asked her reports the same question her boss had asked her.
Now the CEO wants the longest chain between two people, where each step goes along one reporting line. In tree words, this is the diameter: the number of edges on the longest path between any two nodes. Here is the tree for the whole lesson, with letters for its nodes:
The longest path, E → C → B → D → F, never reaches the root.
If B passes the CEO's question down, C answers 1, for E → C. D answers 2, for F → D → G. From 1 and 2, B cannot build 4. D's path bends at D, so B cannot join it.
B needs to know how deep each report's team goes. Both teams are 2 levels deep, so the path that bends at B has 2 + 2 = 4 edges. B asks her reports a different question from the one her boss asked her. This lesson is about choosing that question.
2 Three questions before writing
Before writing a tree function, we answer three questions:
- What does the problem want for the whole tree? This is the CEO's question.
- What must each child tell its parent? This is what each manager asks her reports.
- What does a null child return? This is an empty seat's answer, and it becomes the base case.
As in the tree basics lesson, height counts nodes: 0 for null, 1 for a leaf.
| Problem | 1. Whole tree | 2. Child tells parent | 3. Null returns |
|---|---|---|---|
| Size | number of nodes | number of nodes | 0 |
| Height | height | height | 0 |
| Diameter | longest path | height | 0 |
For size and height, answers 1 and 2 are the same. The function returns the answer itself, and the root's return value is the result.
For the diameter, they differ. The function returns the height, because the parent needs it, and records the longest path in a variable outside the calls. This is the return one thing, record another pattern. In the office, each manager tells her boss how deep her team goes. She also writes the longest path she found on a shared whiteboard, if it beats the one there.
3 Return the height, record the path
Every path has one highest node, where it bends. E → C → B → D → F bends at B. So if each node records the longest path that bends at it, the largest record is the diameter.
That path goes as far down each side as it can. The left height is also the number of edges from the node to its deepest node on the left: one edge to the child, then one per level below it. So:
Each call waits for its two children. Then it works out leftHeight + rightHeight, raises best if that is larger, and returns its own height. The left tree shows the path that bends at each node:
The table lists the calls in the order they finish:
| Node | leftHeight | rightHeight | leftHeight + rightHeight | best | Returns |
|---|---|---|---|---|---|
| E | 0 | 0 | 0 | 0 | 1 |
| C | 1 | 0 | 1 | 1 | 2 |
| F | 0 | 0 | 0 | 1 | 1 |
| G | 0 | 0 | 0 | 1 | 1 |
| D | 1 | 1 | 2 | 2 | 2 |
| B | 2 | 2 | 4 | 4 | 3 |
| A | 3 | 0 | 3 | 4 | 4 |
A returns 4, its height, and nothing uses it. The answer is best, which B wrote on the whiteboard. In code, the helper height is maxDepth from the tree basics lesson with one line added:
On our tree, it returns 4. On a single node and on an empty tree, it returns 0.
C++
best goes in by reference. The helper takes int& best, so every call updates the same variable. Without the &, each call changes its own copy, and the answer stays 0.
best is a field, reset on every call. A method cannot change a caller's int, so best lives in the object. The first line sets it to 0, so a second tree does not start with the first tree's answer.
nonlocal best. The nested height assigns to best. Without nonlocal, Python treats best as a new local variable, and reading it fails with an UnboundLocalError.
A closure. height is defined inside the main function, so it can read and change that call's best. Each new call starts with a fresh best.
Declare the closure first. height calls itself, so it is declared with var before it is assigned. It changes the best of the call that made it.
&mut i32. The helper takes best: &mut i32 and writes *best to change it. Node is a short name for Option<Rc<RefCell<TreeNode>>>.
best is a field, reset on every call. A method cannot change a caller's int without ref, so best lives in the object. The first line sets it to 0, so a second tree does not start with the first tree's answer.
4 When a child must say two things
Balanced Binary Tree asks whether, at every node, the two subtree heights differ by at most 1. The CEO wants a yes or no. But a parent cannot check itself with only a yes from each child. It needs their heights too. So each child must report two things, in one of two ways:
- A signal value. The call returns the height, or −1 when something below it is not balanced. A height is never negative, so −1 cannot be mistaken for one. A parent that gets −1 returns −1 at once, and it travels up to the root.
- A pair. The call returns the height and a yes or no together. It reads more plainly, but it needs a small type for the pair. House Robber III also returns a pair: the best total with the node taken, and without it.
Either way, each node is visited once, and nothing is recorded outside the calls.
5 Returning a node, or a yes or no
Lowest Common Ancestor gives two nodes, p and q, and asks for the lowest node that has both in its subtree. A node counts as part of its own subtree. Each call returns a node, to report what it found:
- Nothing. The call returns null.
- Only p, or only q. The call returns that node, and passes it up.
- Both. One side returned p and the other returned q. This node is the answer, so it returns itself.
A call on p or q returns that node straight away. Here it is with p = E and q = F:
A call can return a yes or no too. In Same Tree, a pair of nodes says yes only if their values match and both pairs of children said yes. The check stops at the first no, so a difference on the left skips the right side entirely. Symmetric Tree compares a tree with its mirror the same way. Path Sum uses both styles from the passing-down lesson: the sum still needed goes down, and a yes or no comes up.
6 Cost, and the trap of asking twice
Each node is called once and, apart from its two calls, does O(1) work. So the time is O(n). The extra space is the call stack, one call per level, so it is O(h): about 17 calls for a balanced tree of 10⁵ nodes, and 10⁵ for a skewed one.
The trap comes from keeping the CEO's question and fetching the heights separately:
diameter(node)
if node is null: return 0
through = height(node.left) + height(node.right)
return max(through, diameter(node.left), diameter(node.right))
The answer is right, but every height call walks a whole subtree again. On a skewed tree of 10⁵ nodes, the walks cover 10⁵ nodes, then 10⁵ − 1, and so on. That is around 5 × 10⁹ steps. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE). In the office, every manager would recount her whole team instead of asking her two reports once.
7 Mistakes and edge cases
- The wrong value for null. Minimum Depth written as 1 + min(left, right), with null as 0, fails on
[2, null, 3]. It returns 1, but the only leaf, 3, is at depth 2. A missing child is not a leaf, so its 0 must not win the min. - The wrong start for the record. Binary Tree Maximum Path Sum allows negative values. If
beststarts at 0, the tree[-3]gives 0 instead of −3. The record must start below any possible answer. - Keeping a branch that hurts. In a path sum, a parent takes max(0, child's sum), so a negative branch is left out. Without it,
[1, -5, 3]gives 3 instead of 4, the sum of 1 → 3. - Returning the record instead of the height. If
heightreturns leftHeight + rightHeight, every call on our tree returns 0, and so does the diameter. - A whiteboard nobody wipes. If
bestlives outside the function and is set to 0 only once, the next tree starts with the last answer. After our tree,[7]gives 4 instead of 0.
8 When to use it
The sign is that the answer for a node depends on the answers for its children. Then the three questions decide the code. Here is what each call returns in this group's main problems:
| Problem | Each call returns | Also records |
|---|---|---|
| Maximum Depth | its height | nothing |
| Invert Binary Tree | the root of the flipped subtree | nothing |
| Same Tree, Symmetric Tree | yes or no | nothing |
| Balanced Binary Tree | its height, or −1 | nothing |
| Diameter of Binary Tree | its height | longest path bending here |
| Binary Tree Maximum Path Sum | best sum going down from it | best sum bending here |
| Lowest Common Ancestor | null, p, q or the answer | nothing |
| House Robber III | best with it and without it | nothing |
A few problems in the group carry a value down instead, as in the passing-down lesson. Count Good Nodes carries the largest value on the path so far, and Binary Tree Paths carries the path itself.
The next lesson leaves depth first behind. It visits the tree level by level, with a queue.
Before writing a tree function, answer the three questions on paper: what the whole tree needs, what a child must tell its parent, and what a null child returns. If the first two differ, return the second and record the first.
Practice it
- Maximum Depth of Binary TreeEasy
- Invert Binary TreeEasy
- Same TreeEasy
- Subtree of Another TreeEasy
- Balanced Binary TreeEasy
- Diameter of Binary TreeEasy
- Count Good Nodes in Binary TreeMedium
- Binary Tree PathsEasy
- Lowest Common Ancestor of a Binary TreeMedium
- Binary Tree Maximum Path SumHard
- Boundary of Binary TreeMedium
- Minimum Depth of Binary TreeEasy
- Symmetric TreeEasy
- Merge Two Binary TreesEasy
- Path SumEasy
- Path Sum IIMedium
- Sum Root to Leaf NumbersMedium
- Path Sum IIIMedium
- Children sum propertyMedium
- Path from the root to a nodeMedium
- Count Complete Tree NodesMedium
- Flatten Binary Tree to Linked ListMedium
- House Robber IIIMedium
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.