Lesson 3 of 5
Passing answers up the tree
At every node of a tree, ask two questions. What do I need from my children? What do I hand to my parent? Diameter, balanced trees, path sums and lowest common ancestors are four answers to that pair.
Ask the two questions at every node before writing a tree function, and say what travels up, what travels down and what is kept on the side
Return what the parent needs while recording the answer in an outside variable with
nonlocalFold a failure signal into a return value so that one walk both measures and checks
Pass what a node needs from above down to it as an argument
Find the lowest common ancestor by letting each subtree report what it found
A shared drive is a tree of folders, and two reports about it come up all the time. A folder's total size is its own files plus the totals of its subfolders, so a folder can answer only after its subfolders have: the answer travels up. A folder's full path is its parent's path plus its own name, so a folder needs its parent's answer first: the information travels down.
Tree problems in interviews are built from the same two moves. Last lesson's max depth used the first: each node asked its children for their depths and handed one more than the larger to its parent. This lesson gives that shape four twists, one per classic problem, and asks the same pair of questions at every node: what do I need from my children, and what do I return to my parent?
Answers travel up
How does one call hand its answer to another? First, a reminder of the words from the binary trees lesson. A binary tree is made of nodes. Each node (a TreeNode in this lab) holds a value, val, and two links, left and right, each pointing at a child node or at None. A node with no children is a leaf. A node together with everything below it is its subtree. The height of a subtree is the number of nodes on its longest downward path, and an empty subtree has height 0. Last lesson's max depth is the height of the root.
build_tree([1, 2, 3, 4]) builds a tree from its levels, read left to right: 1 on top, 2 and 3 below it, and 4 as the left child of 2. The trace finds its height. The state panel draws the tree and one box for each call that has started and not yet returned. Before you step through, guess: apart from the calls on empty children, which node's call returns first?
def height(node):if node is None:return 0left = height(node.left)right = height(node.right)return 1 + max(left, right)
(nothing printed yet)Every node returned after both of its children. That order, children before parent, is the postorder of the binary trees lesson, and the code forces it: a call cannot reach line 6 until lines 4 and 5 have their answers. The return value is the only note a call hands on, and its parent stores it in left or right.
Here is the same walk with a print added once both children have answered. Predict the order of the lines.
This is height from the trace with a print added after both children have answered. Type exactly what it prints: one line per node, its value, a space, then its height.
The tree is [1, 2, 3, None, 4, 5]: 1 on top with children 2 and 3; node 2 has only a right child, 4; node 3 has only a left child, 5.
def height(node):
if node is None:
return 0
left = height(node.left)
right = height(node.right)
h = 1 + max(left, right)
print(node.val, h)
return h
height(build_tree([1, 2, 3, None, 4, 5]))
The space depends on the number of levels, not the number of nodes. Count the open boxes on a tree that is all levels.
height from the trace runs on a chain of 5 nodes, each the left child of the one above: build_tree([1, 2, None, 3, None, 4, None, 5]). At the busiest moment, how many height boxes are open at once? Count the call on an empty child too. Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Return one thing, record another
What if the parent needs something other than the answer? A path in a tree is a chain of nodes, each joined to the next by a parent and child link, with no node used twice. Its length is its number of links, called edges. The diameter of a tree is the length of its longest path. A path may climb from one node and come down to another, and it need not pass through the root.
Every path has one highest node, where it turns. It climbs one side to that node and goes down the other side, or ends there. The longest path that turns at a node goes as deep as it can on each side, so it has height(node.left) + height(node.right) edges: each node on the deepest route down one side adds one edge, counting the edge from the turning node to its child. In the first trace's tree, the root's sides have heights 2 and 1, and the longest path that turns there, 4, 2, 1, 3, has 2 + 1 = 3 edges.
Can each call return its subtree's diameter, the way heights went up? No: a parent cannot build on its child's diameter. The longest path inside the child's subtree may turn deep down and never touch the child. What a parent can extend is the longest downward path from its child, and that is the child's height.
So each call returns what its parent needs, its height, and records the answer on the side: the longest turn at its node goes into best, a variable of the outer function diameter. height sits inside diameter, the way visit sat inside preorder in the binary trees lesson, so it can read best. Changing it takes one more line. visit only called out.append(...), which changes the list without assigning to the name out. height assigns, best = ..., and a name that a function assigns to belongs to that function, unless a nonlocal line says it belongs to the function around it. nonlocal best says exactly that.
The tree is [1, None, 2, 3, 4, None, 5, 6]: the root 1 has only a right child, 2. Node 2 has children 3 and 4, node 3 has a right child 5, and node 4 has a left child 6.
1
\
2
/ \
3 4
\ /
5 6
Find the longest path by hand, then guess at which node best reaches it.
def diameter(root):best = 0def height(node):nonlocal bestif node is None:return 0left = height(node.left)right = height(node.right)best = max(best, left + right)return 1 + max(left, right)height(root)return best
(nothing printed yet)The answer was found at node 2, below the root, and no parent ever saw it. Each call hands up only what its parent can use, and the answer collects on the side.
The nonlocal line is the one people forget, and the error it causes is worth knowing on sight.
This is the traced diameter with the line nonlocal best deleted:
def diameter(root):
best = 0
def height(node):
if node is None:
return 0
left = height(node.left)
right = height(node.right)
best = max(best, left + right)
return 1 + max(left, right)
height(root)
return best
What happens on diameter(build_tree([1, 2, 3]))?
Choose one answer, then check.
Now write the same shape for a new question. The parent needs a sum, and the answer adds up something else.
The tilt of a node is the absolute difference (the difference without its sign, abs(a - b)) between the sum of all values in its left subtree and the sum of all values in its right subtree. An empty subtree sums to 0. Write total_tilt(root), which returns the sum of the tilts of every node (0 for an empty tree).
In [1, 2, 3, 4], node 2's tilt is abs(4 - 0) = 4, the root's is abs(6 - 3) = 3 (its left subtree holds 2 and 4), and each leaf's is 0, so the answer is 7. Then press Watch it run.
raise NotImplementedError, then press Run tests. Each check says what it expects.Now the problem itself. Try it from a blank editor before you open the hints.
The solution is the function you traced. Two details catch people. Heights count nodes, while left + right counts edges, because the turning node is on neither side. And the brute force, measuring both heights from scratch at every node, measures a deep subtree again for every node above it: O(n·h) time instead of O(n), and O(n2) for a chain.
Two kinds of news in one number
What if a child needs to report that something is wrong? A tree is balanced when, at every node, the heights of the left and right subtrees differ by at most 1. Every node must pass, not only the root. A root with two sides of equal height can still hide a lopsided node lower down.
Checking each node with a separate height function works, but it measures the same subtrees again for every node above them. One walk can measure and check at once if a call can send two kinds of news: "my subtree is balanced and this tall", or "something in here is out of balance". A height is never negative, so -1 is free to mean failure. A call returns -1 as soon as a child returns -1 or its two heights differ by more than 1, and its height otherwise.
The tree is [1, 2, 3, 4, None, None, None, 5]: the root 1 has children 2 and 3, and below 2 hangs a chain, with 4 as its left child and 5 as the left child of 4. Before you step through, guess which node first returns -1, and whether the walk ever reaches node 3.
def is_balanced(root):def height(node):if node is None:return 0left = height(node.left)if left == -1:return -1right = height(node.right)if right == -1 or abs(left - right) > 1:return -1return 1 + max(left, right)return height(root) != -1
(nothing printed yet)Once -1 appears, every call above it returns -1 at once, and the walk stops at the first node out of balance.
Work one by hand, with the failure on the right side this time.
On paper, work out what height from the balanced trace returns at every node of [1, 2, 3, 4, 5, None, 6, None, None, None, None, None, 7], bottom up.
The root 1 has children 2 and 3. Node 2 has two leaf children, 4 and 5. Node 3 has only a right child, 6, and 6 has only a right child, 7.
Then count how many of the seven calls on real nodes return -1.
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
The problem asks for exactly this check. Write it without looking back at the trace.
The rule compares two sibling subtrees, not the levels of leaves. In [1, 2, 3, 4], leaf 3 sits one level higher than leaf 4, and the tree is balanced. Check every -1 before you use it as a height. Next to an empty side's 0, a -1 differs by only 1, so a call that skips the check sees no problem, returns 1 + max(0, -1), which is 1, and the failure vanishes. A pair (balanced, height) would also carry both kinds of news; -1 is the shortest way.
Passing information down
What if a node needs something only its parent knows? A root-to-leaf path starts at the root and follows child links down until it stops at a leaf. Path sum asks: does some root-to-leaf path add up to exactly a target?
A node cannot see the path above it. Only its parent knows how much of the target is still missing, so the parent tells it, as an argument. Each call subtracts its own value and hands the rest, remaining, to its children, which receive it as their target. Return values travel up; arguments travel down. A call uses what it receives before it asks its children, so this walk goes parent before children: the binary trees lesson's preorder.
Check only at a leaf. A path must end at a leaf, so a node with a child ends no path, even when remaining is 0 there.
The tree is [3, 5, 1, 2, None, None, 4]: the root 3 has children 5 and 1, node 5 has a left child 2, and node 1 has a right child 4. Its root-to-leaf paths add up to 3 + 5 + 2 = 10 and 3 + 1 + 4 = 8. The target is 8. Before you step through, guess what remaining is at node 5, and whether the walk stops there.
def has_path_sum(root, target):if root is None:return Falseremaining = target - root.valif root.left is None and root.right is None:return remaining == 0return has_path_sum(root.left, remaining) or has_path_sum(root.right, remaining)
(nothing printed yet)a or b skips b when a is True. Had node 5's side found a path, the call on node 1 would never have started: one good path is enough.
Here is the down direction on its own: a depth handed from parent to child. Predict the order of the lines.
Here a depth travels down: each call prints its node and the depth its parent handed it, then passes depth + 1 to its children. Type exactly what it prints.
The tree is the one from the path sum trace, [3, 5, 1, 2, None, None, 4]: 3 on top with children 5 and 1; node 5 has a left child 2; node 1 has a right child 4.
def show_depths(node, depth):
if node is None:
return
print(node.val, depth)
show_depths(node.left, depth + 1)
show_depths(node.right, depth + 1)
show_depths(build_tree([3, 5, 1, 2, None, None, 4]), 1)
Some problems need both directions. In this one a number travels down each path, and totals travel back up.
Each root-to-leaf path spells a number, one digit per node, read from the top: in [1, 2, 3] the two paths spell 12 and 13. Put the lines in order to build sum_numbers(node, number=0), which returns the sum of all the numbers spelled. number is what the path above has spelled so far, handed down by the parent. Indentation is already part of each line. Two lines do not belong.
Add lines from the list below, in order.
return sum_numbers(node.left, number) + sum_numbers(node.right, number)if node.left is None and node.right is None:number = number * 10 + node.valif node is None:return numberreturn 0def sum_numbers(node, number=0):number = number + node.valif node.left is None or node.right is None:
Now path sum itself.
The reference solution is the traced function, line for line. Two of its tests are this section's traps: [1, 2] with target 1, where the root has a child and so ends no path, and the empty tree, which gives False even for target 0. Values can be negative, so a sum that has passed the target can come back down: never stop early because of it.
Reporting what you found
What should a call return when its parent needs to know what was found below? An ancestor of a node is any node on the way from the root down to it, and a node counts as its own ancestor. The lowest common ancestor of two nodes p and q is the ancestor of both that is farthest from the root. Picture the path from the root down to p and the path down to q: they share a top part and then split, and the last shared node is the answer.
So each call returns one node or None, and its parent reads that report three ways:
None: neither target is in that subtree.porq: a target is there. A call that reachesporqreturns it at once, without looking below.- any other node: the finished answer, found deeper down.
If both children report a node, p is on one side and q on the other, so this node is the answer. If only one does, the call passes that report up.
p and q are nodes, not values, so the code compares with is, which (as in the linked lists module) asks whether two names point at the very same object. The tree is [1, 2, 3, 4, 5]: the root 1 has children 2 and 3, and node 2 has children 4 and 5. tree.left.left is node 4 (p) and tree.left.right is node 5 (q). Before you step through, guess what the call on node 3 returns.
def lowest_common_ancestor(root, p, q):if root is None or root is p or root is q:return rootleft = 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 rootreturn left if left is not None else righttree = build_tree([1, 2, 3, 4, 5])answer = lowest_common_ancestor(tree, tree.left.left, tree.left.right)print(answer.val)
(nothing printed yet)Now the case where one target sits below the other.
Run lowest_common_ancestor from the trace on the same tree, [1, 2, 3, 4, 5], but with p as node 2 and q as node 5, which sits below node 2. What does it return, and does any call ever reach node 5?
Choose one answer, then check.
The problem uses a bigger tree and the same code. Try it from scratch.
Returning the moment a call reaches p or q is safe only because both are promised to be in the tree. If one might be missing, finding p proves nothing about q; the problem's follow-ups show what changes.
Choosing the direction
Height and the four problems, one pair of questions, side by side:
| Problem | Needs from its children | Returns to its parent | Kept on the side | Passed down |
|---|---|---|---|---|
| Height | their heights | its height | nothing | nothing |
| Diameter | their heights | its height | best, the longest turn | nothing |
| Balanced | their heights, or -1 | its height, or -1 | nothing | nothing |
| Path sum | True or False from each | True or False | nothing | how much is still needed |
| Lowest common ancestor | a node or None from each | a node or None | nothing | p and q, unchanged |
Read a new tree problem by filling in its row. If a node's answer depends only on what is below it, return it up. If it depends on what is above it (the path so far, a running total), pass it down as an argument. If the parent cannot use the answer, return what it can use and record the answer on the side. Every row costs at most one visit per node: O(n) time and O(h) space for the call stack. Plain Python stops at about 1,000 nested calls by default (this lab allows 5,000), so a tree deeper than that needs an explicit stack; the problems' follow-ups show how.
Last, say one row out loud for a problem you have not seen.
An interviewer asks for the largest subtree sum: the largest total of the values in any subtree (a node plus everything below it). The tree has at least one node, and values can be negative. Before typing, explain your plan in a few plain sentences: what each call returns to its parent, what you keep on the side and what it starts as, and the walk, the promise and the cost.
Saved in this browser as you type.