Four interview problems that answer a question about a tree with one pass of recursion. The move: return one thing to the parent, and record the answer that bends at this node on the side.
You work on a dispute tool, a budget tool, a call tracer and an org chart. The four problems on this street come from them, and each one asks a question about a whole tree. One recursive pass answers it.
Here is what a call returns to its parent, and what it records on the side.
| Problem | The call returns | The call records |
|---|---|---|
| Shortest path to a dispute outcome | the depth of the nearest leaf below | nothing: the answer is what the root returns |
| Paths of any start summing to k | nothing: it carries a map of prefix sums down | the paths that end at this node |
| Smallest subtree holding the deepest nodes | the depth and the root of the best subtree | nothing: the answer travels up |
| Best path sum through the org chart | the best chain going down | the best path that bends at this node |
In the first three rows the answer is what the root returns. In the last row it is not, and that difference is the point of this street.
Exercise · Predict the output: The best path through the chart. Node i has its value in values[i] and its children in left[i] and right[i], with -1 for none. Every child has a larger index than its parent. A path may bend at one node. What does the code print?
values = [-10, 9, 20, 15, 7]
left = [1, -1, 3, -1, -1]
right = [2, -1, 4, -1, -1]
n = len(values)
down = [0] * n
best = -1000000000
for i in range(n - 1, -1, -1):
lo = down[left[i]] if left[i] != -1 else 0
hi = down[right[i]] if right[i] != -1 else 0
lo = max(lo, 0)
hi = max(hi, 0)
best = max(best, values[i] + lo + hi)
down[i] = values[i] + max(lo, hi)
print(best)Decide two things before you write the recursion. What does a call give back to its parent, and what does it keep for the final answer?
A call returns what its parent can build on, and records the best answer that is complete at this node. The two differ when the answer can use both children but the parent can extend only one of them.
You can see the split in the last two problems.
A call returns the better chain to its parent and records the path that bends at the node: 42, not 35.
Exercise · Find the bug: The leaf that is not a leaf. This returns the depth of the shallowest leaf, with the root at depth 1. Node i has children left[i] and right[i], or -1, and every child has a larger index. One input gives an answer that is too small. Which line is wrong?
def shallowest_leaf(left, right):
n = len(left)
depth = [0] * n
for i in range(n - 1, -1, -1):
lo = depth[left[i]] if left[i] != -1 else 0
hi = depth[right[i]] if right[i] != -1 else 0
depth[i] = 1 + min(lo, hi)
return depth[0]The Academy lessons Trees and search trees, Tree recursion and Lowest common ancestor teach the recursion and its common questions. This street changes three things.
The edge case is the structure. A node with one child is not a leaf. Take a tree whose root has only a left child. The shallowest leaf is at depth 2, but a version that counts a missing child as depth 0 returns 1.
Paths start anywhere. A chain of 100,000 nodes has 5,000,050,000 downward paths, so you cannot try them one at a time. One map of prefix sums along the current path lets each node count the paths that end at it with one lookup.
A call returns two facts. For the deepest leaves, the call returns a depth and a root. Take the tree where node 0 has children 1 and 2, and node 1 has children 3 and 4. The deepest leaves are 3 and 4, so the answer is node 1.
A path can start at any node, so adding up only the paths from the root misses paths that start lower.
Exercise · Break it: The paths that start low. This counts the downward paths whose values add up to k. Node i has its value in values[i], and its children in left[i] and right[i] or -1. Find an input where it gives the wrong count.
def count_paths(values, left, right, k):
n = len(values)
parent = [-1] * n
for i in range(n):
if left[i] != -1:
parent[left[i]] = i
if right[i] != -1:
parent[right[i]] = i
count = 0
for i in range(n):
total = 0
node = i
while node != -1:
total += values[node]
node = parent[node]
if total == k:
count += 1
return countSolve them in this order. The first returns one number, the second carries a map, the third returns two facts, and the fourth returns one fact and records another.
Before you code each problem, write two lines: what a call returns to its parent, and what it records on the side. If the second line is empty, the answer is what the root returns.
Give each problem about 25 minutes. Draw a tree of five nodes, and write beside each node what its call returns and what it records.
Test a tree of one node, a tree where every node has one child, and a tree with negative values. Check each of these on paper first. Most wrong answers here come from treating a missing child as a real one, or from returning a value the parent cannot extend.
Checkpoint · Depth, paths and ancestors
Q1/5 In the best path sum, what does a call return to its parent?
Answer: B
A parent can extend only one chain downwards, so the call returns the better one. The path that bends at the node is recorded on the side.
Q2/5 For the values -10, 9, 20, 15, 7 in the tree from the lesson, what is the best path sum?
Answer: C
The path 15, 20, 7 bends at the node 20 and adds up to 42. The best chain going down from 20 is 35, and the path through the root is 34.
Q3/5 A root has only a left child, and that child is a leaf. What is the depth of the shallowest leaf, with the root at depth 1?
Answer: B
A node with a child is not a leaf. The only leaf is the child, at depth 2.
Q4/5 Why are the paths that start at any node counted with a map of prefix sums?
Answer: B
One map along the current path lets each node count the paths that end at it with one lookup, instead of trying every start.
Q5/5 For the deepest leaves, what does a call return when both children are equally deep?
Answer: B
When both sides are equally deep, this node is the smallest root that holds the deepest leaves on both sides, so it returns itself.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.