Solve a tree by combining what each subtree returns (height, balance, diameter) and by passing a running total down a path.
You are building the admin page of a company directory. It shows an org chart: every person has at most two direct reports, a left one and a right one.
Your team lead asks for four things:
You answered the first of these in the last lesson, by walking every node. This lesson gives you one method for all four.
Each question is answered by combining the answers of the two smaller charts below a person, or by handing a number down.
A school closes for snow, and the head teacher starts a phone tree. The head calls two people. Each of them calls two more, and so on down the tree. Every call carries a message and a count of how many calls it took to reach you.
Afterwards, everyone reports back up. A person cannot report "everyone below me was reached" until both of the people they called have reported. Then they add themselves and report to the person who called them.
Here is how this maps to a tree. The message and the count go down, as arguments. The reports go up, as return values. Each person is a node, and the people they called are its children.
A snow-day phone tree: the message goes down the tree, and the reports come back up. Each person waits for both people they called.
A recursive function on a tree calls itself on the left child and on the right child. This works because every child is the root of a smaller tree. Four words describe every such function.
Answers come up, in return values. A node can only combine what its children return once both calls have finished, so the children are handled first. This is the post-order of the last lesson.
Values go down, in arguments. A node must receive its value before it can pass one on to its own children, so the parent is handled first, as in pre-order.
Before you write any code, decide which kind of question you have. Ask: does a node's answer depend on what is below it, or on the way from the root to it?
| Question | Depends on | Direction | What the call returns | What the call receives |
|---|---|---|---|---|
| How many levels? | The subtrees | Up | The height of this subtree | Only the node |
| Is it balanced? | The subtrees | Up | The height, or -1 for "not balanced" |
Only the node |
| Longest path? | The subtrees | Up, plus a best kept on the side | The height | Only the node |
| A root-to-leaf path with a total? | The way from the root | Down | Found or not | What is left of the total |
| Every such path? | The way from the root | Down | Nothing: matches are saved | What is left, and the path so far |
This lesson keeps the conventions of the last one. Depth counts links down from the root, so the root has depth 0. Height counts levels, so an empty tree has height 0 and a single node has height 1.
A path is counted in links. A path from one node to another that is next to it has 1 link. Some books count height in links and paths in nodes. State which one you use, as the checker for a problem will not guess it.
Step by step: A tree in memory. The animated player loads in your browser.
Predict what happens
Q A tree has a root with one child, and that child has one child. What do height(root) and height(the middle node) return, counting levels?
Answer: B
The bottom node is a leaf: 1 plus the larger of 0 and 0 is 1. The middle node is 1 plus 1, which is 2. The root is 1 plus 2, which is 3.
We use one tree for the first examples. The numbers are only labels here.
40
/ \
25 60
/ \ \
10 30 70
\
35The height of a tree is 1 plus the larger of its two subtree heights. An empty tree has height 0.
def height(node):
if node is None:
return 0
return 1 + max(height(node.left), height(node.right))Trace it from the bottom up. Each row is a call that has finished.
| Node | Left returned | Right returned | Returns |
|---|---|---|---|
| 10 | 0 | 0 | 1 |
| 35 | 0 | 0 | 1 |
| 30 | 0 | 1 (node 35) | 2 |
| 25 | 1 (node 10) | 2 (node 30) | 3 |
| 70 | 0 | 0 | 1 |
| 60 | 0 | 1 (node 70) | 2 |
| 40 | 3 (node 25) | 2 (node 60) | 4 |
The tree has 4 levels. Each node returns only one number, and the work at each node is one comparison.
Height is one plus the taller of the two subtree heights, and an empty tree is zero. Each call returns one number to its parent.
Step by step: Post-order: every child before its parent. The animated player loads in your browser.
A tree is balanced when, at every node, the heights of the left and right subtrees differ by at most 1. Checking the root alone is not enough, because the trouble can be low down.
A direct way calls height at every node. That repeats work: a node deep in the tree is measured again for every node above it. Instead, return the height when the subtree is balanced, and -1 when it is not. A parent that sees -1 returns -1 at once.
def check(node):
if node is None:
return 0
lh = check(node.left)
if lh == -1:
return -1
rh = check(node.right)
if rh == -1 or abs(lh - rh) > 1:
return -1
return 1 + max(lh, rh)Use this tree, where node 25 is the problem:
40
/ \
25 60
/ / \
10 50 70
/
5The calls run check(40), check(25), check(10) and check(5). Then they finish in the opposite order.
check(5) returns 1.check(10) has lh = 1 and no right child, so it returns 2.check(25) has lh = 2 and rh = 0, a difference of 2, so it returns -1.check(40) sees -1 from its left call. It returns -1 without looking at 60, 50 or 70.The check stopped after 4 of the 7 nodes. The root alone would not have found the problem: its two sides are 3 and 2 levels deep, which differ by only 1.
Exercise · Put it in order: The one-pass balance check. The tree is kept as two lists: left[i] and right[i] are the children of node i, or -1 for none. Arrange the lines into a function that returns the height in levels of the subtree at `node` when it is balanced, and -1 when it is not. A -1 from the left side must stop the check at once.
def check(left, right, node):
if node == -1:
return 0
lh = check(left, right, left[node])
if lh == -1:
return -1
rh = check(left, right, right[node])
if rh == -1 or abs(lh - rh) > 1:
return -1
return 1 + max(lh, rh)
return max(lh, rh)Why not call height at each node and compare? That is correct too, but it measures the same subtrees again and again. A node at depth d is measured once for each of the d nodes above it. How much that costs depends on the tree and on when the check stops.
The one-pass check returns the height and the signal together, so every node is visited once, on any tree.
Exercise · Break it: Find the tree this check calls balanced. This function says a tree is balanced when the heights of the root's two sides differ by at most 1. Find a tree it calls balanced that is not, because some node lower down is out of balance. The tree is a list in level order, left to right, row by row, where -1 means "no node" (every real id is positive).
def is_balanced(root):
if root is None:
return True
return abs(height(root.left) - height(root.right)) <= 1Predict what happens
Q In the tree above, check(10) returns 2. What does check(25) return, and why?
Answer: C
The left call returns 2, the right call returns 0 for the missing child, and 2 and 0 differ by 2. That is more than 1, so 25 returns the signal -1.
The diameter is the largest number of links on a path between any two nodes. The path goes up from one node to a highest node, and then down to another. That highest node is where it turns.
The path may miss the root. Use this tree.
90
/
50
/ \
30 70
/ \
20 80
\
85At each node, two numbers matter. Best through this node is left height plus right height, in links. Returned upward is 1 plus the taller side, in levels. The parent can only extend one side, so it gets the second number.
def diameter(root):
best = 0
def walk(node):
nonlocal best
if node is None:
return 0
lh = walk(node.left)
rh = walk(node.right)
best = max(best, lh + rh)
return 1 + max(lh, rh)
walk(root)
return best| Node | Left height | Right height | Best through (links) | Returned upward |
|---|---|---|---|---|
| 20 | 0 | 0 | 0 | 1 |
| 30 | 1 | 0 | 1 | 2 |
| 85 | 0 | 0 | 0 | 1 |
| 80 | 0 | 1 | 1 | 2 |
| 70 | 0 | 2 | 2 | 3 |
| 50 | 2 | 3 | 5 | 4 |
| 90 | 4 | 0 | 4 | 5 |
The diameter is 5: the path 20, 30, 50, 70, 80, 85. It turns at 50 and never touches the root 90. At the root, the best through it is only 4.
The longest path turns at one node, where the best path is left height plus right height. The node returns only one plus its taller side.
Step by step: Post-order on a tree whose longest path misses the root. The animated player loads in your browser.
Exercise · Predict the output: What does the diameter code return?. The code below finds the diameter, the most links on a path between two nodes, using the one-pass method. The tree has the root 1 with only a left child 2. Node 2 has the children 3 and 4, and node 3 has the children 5 and 6, and node 4 has the children 7 and 8. What does it print?
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def diameter(root):
best = 0
def walk(node):
nonlocal best
if node is None:
return 0
lh = walk(node.left)
rh = walk(node.right)
best = max(best, lh + rh)
return 1 + max(lh, rh)
walk(root)
return best
root = Node(1, Node(2, Node(3, Node(5), Node(6)), Node(4, Node(7), Node(8))))
print(diameter(root))Predict what happens
Q A tree is a chain of 4 nodes, going down one side. What is its diameter, and what is the left height plus the right height at the top node?
Answer: B
The 4 nodes are joined by 3 links, so the path from the top to the bottom has 3 links. At the top, one side is 3 levels deep and the other is empty, so left plus right is 3 as well.
Some questions depend on the path from the root, not on the subtrees. "Is there a root-to-leaf path that adds up to 16?" Hand down what is left of the budget.
Subtract this node's value, and pass the rest to each child. At a leaf, the rest must be 0.
def has_total(node, remaining):
if node is None:
return False
remaining -= node.value
if node.left is None and node.right is None:
return remaining == 0
return has_total(node.left, remaining) or has_total(node.right, remaining)Use the root 7, with the children 3 and 9. Node 3 has the children 4 and 6, and node 9 has only a right child, 2. Start with 16.
| Call | Remaining after this node | What happens |
|---|---|---|
| node 7 | 9 | not a leaf: go on |
| node 3 | 6 | not a leaf: go on |
| node 4 | 2 | a leaf, and 2 is not 0: false |
| node 6 | 0 | a leaf, and 0: true |
The path 7, 3, 6 adds up to 16. The calls for node 9 never run, because the or already has its answer.
A missing child must return false, not remaining == 0. A node with one child is not a leaf, and a missing child is not a path.
To find a root-to-leaf path with a total, hand down what is left of the budget. Only a leaf with nothing left means a path was found.
Exercise · Find the bug: The path that stops at a node with one child. This function should say whether some path from the root down to a leaf adds up to the total. It sometimes says yes when every full path misses the total. Which line is wrong?
def has_total(node, remaining):
if node is None:
return False
remaining -= node.value
if node.left is None or node.right is None:
return remaining == 0
return has_total(node.left, remaining) or has_total(node.right, remaining)To list every root-to-leaf path with a total, keep one list for the path so far. Add this node's value, explore both children, and remove it again. Copy the list only when a path matches.
def all_paths(node, remaining, path, found):
if node is None:
return
path.append(node.value)
remaining -= node.value
if node.left is None and node.right is None and remaining == 0:
found.append(list(path))
all_paths(node.left, remaining, path, found)
all_paths(node.right, remaining, path, found)
path.pop()Use the root 5 with the children 3 and 4. Node 3 has the children 1 and 2, and node 4 has the left child 0. Start with 9.
Trace the one shared list. Each row is one step of the walk.
| Step | path after the step |
Left of 9 | What happens |
|---|---|---|---|
| visit 5 | [5] |
4 | not a leaf: go on |
| visit 3 | [5, 3] |
1 | not a leaf: go on |
| visit 1 | [5, 3, 1] |
0 | a leaf with 0 left: save a copy |
| leave 1 | [5, 3] |
undo: pop 1 | |
| visit 2 | [5, 3, 2] |
-1 | a leaf, but -1 is not 0 |
| leave 2 and 3 | [5] |
undo: pop 2, then 3 | |
| visit 4 | [5, 4] |
0 | not a leaf, so 0 left does not count yet |
| visit 0 | [5, 4, 0] |
0 | a leaf with 0 left: save a copy |
| leave 0, 4, 5 | [] |
undo all three |
The path 5, 3, 1 adds up to 9, and so does 5, 4, 0. The answer is [[5, 3, 1], [5, 4, 0]]. At the end the shared list is empty again, which is why each saved path must be a copy.
This pattern is called backtracking: add, explore, undo. The next lessons use it for subsets and arrangements.
A recursive call waits while its children run. So the number of calls waiting at once is the height of the tree. A balanced tree of a million nodes is about 20 levels tall, and 20 waiting calls are nothing.
A chain is different. A chain of 1,000 nodes has 1,001 calls waiting, counting the one for the missing child. Python's default limit is about 1,000 nested calls, so height on a chain of 1,000 nodes fails with a RecursionError. A chain of 500 nodes works.
Java, C++ and JavaScript allow deeper calls, and how deep depends on settings and on the size of each call. A chain of 100,000 nodes can still overflow them. Raising Python's limit can crash the program instead of failing cleanly.
There are two safe fixes, and neither needs recursion.
Here is the height with no recursion, on a tree stored as arrays, as in the warm-ups. Node 0 is the root, and left[i] and right[i] are the children of node i, or -1.
def height(left, right):
if not left:
return 0
order = [0]
for node in order:
for child in (left[node], right[node]):
if child != -1:
order.append(child)
h = [0] * len(left)
for node in reversed(order):
lh = h[left[node]] if left[node] != -1 else 0
rh = h[right[node]] if right[node] != -1 else 0
h[node] = 1 + max(lh, rh)
return h[0]The first loop grows order while it reads it, so it lists every node, parents first. The second loop is the recursive function's combine step, in the order in which the calls would have finished. On the first tree of this lesson, order is 40, 25, 60, 10, 30, 70, 35. The backward pass fills 35, 70, 30, 10, 60, 25 and 40, each from children already done.
The warm-up problems below use these, so a chain of 100,000 nodes is no trouble.
Predict what happens
Q You run the recursive height function in Python on a tree that is a chain of 5,000 nodes. What happens?
Answer: B
Each call waits for the call below it, so the deepest call is 5,000 levels down. The default limit is about 1,000, so Python raises a RecursionError.
All the tasks in this lesson look at every node at most once. The table shows the steps, and also how many calls wait at once, which is what decides whether recursion is safe.
| Operation | Steps on a balanced tree | Steps on a chain | Calls waiting at once (recursive) | What sets the cost |
|---|---|---|---|---|
| Insert a value into a search tree | About log n: one path | n | The height | The height: only one path is followed |
| Search for a value | About log n | n | The height | The height |
| Delete a value | About log n | n | The height | Finding the node, then maybe the successor |
| Walk every node (any order) | n | n | The height | Every node is visited once |
| Height of the tree | n | n | The height | Every node must report |
| Check that the tree is balanced, in one pass | At most n | At most n: it stops at the first problem | The height | The calls stop early on a problem |
Check balance by calling height at every node |
About n log n | About n^2 / 2 if it checks every node | The height | Each node is measured again for every node above it |
| Diameter | n | n | The height | Every node is a possible turn |
| Path with a total, or every path | At most n, plus the size of the answer | At most n | The height | Paths share their beginnings |
Searching, inserting and deleting follow one path, so they cost the height. Every question in this lesson needs information from all the nodes, so it costs n. On a balanced tree the calls waiting are few. On a chain they are n, and that is the reason to use a loop.
Use the sandbox to see the order in which answers become ready. A post-order walk visits every child before its parent. That is the order of the table of heights above.
Try these five, in order:
diameter would give if you looked only at the root.The sandbox: build a list and run its operations step by step. It loads in your browser.
Now build a search tree that stores its answers. The lab gives you a HeightTree class. Every node has a value, a left link, a right link and a height field, and all four are ready for you. You write five methods: insert, height, height_of, is_balanced and diameter.
The idea is to store, in each node, the answer that the recursion would compute. An insert changes only the nodes on its path. So after adding a node, walk back up the path from the bottom, and recompute each node's height from its two children. At each of them, also update the best path that turns there.
Three things to take care over:
height counts levels: 0 for an empty tree and 1 for one node. diameter counts links, so one node gives 0.insert ignores a value that is already there and returns false. It must not change any stored height then.Each test creates a new, empty tree, calls your methods in order and compares every value they return. When a test fails, the result names the exact call that went wrong, the value it returned and the value it should return.
Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Combine the subtrees when the answer about a node depends on the answers about its children. Examples are a total size, a height, a balance, the best path, and whether two trees match.
Hand a value down when the answer depends on the way from the root. Examples are a budget left, the path so far, and a permission inherited from a folder.
Each node is handled once, so the work is n steps. Keep the depth in mind: for a tree that can be a long chain, use a loop.
If only one path matters, such as searching a search tree, there is nothing to combine. Follow the path with a loop. If the data can contain a cycle, such as a graph, recursion that never marks what it has visited can run forever. Mark each node as visited, or use the graph methods of a later lesson.
best = height(root.left) + height(root.right) is the longest path that goes through the root. In the tree 90, 50, 30, 70, 20, 80, 85 it gives 4 + 0 = 4, and the diameter is 5, from 20 to 85. The longest path turns at the node 50. Take left plus right at every node, and keep the largest.
A common mistake: taking left height plus right height at the root only. The longest path can turn lower down, and here it has five links against four.
if remaining == 0: return True at any node, or if node is None: return remaining == 0, accepts a path that stops halfway. Take the root 5 with one child 4, and the total 5.
The first version returns true at the root. The second returns true at the missing child of the root. The only root-to-leaf path is 5 then 4, which adds up to 9. Return the result at a leaf only, and return False for a missing child.
found.append(path) saves a reference to the list that the walk keeps changing. Take the root 5, the children 3 and 4, and the total 9 from the example above. The answer ends up as [[], []], because the walk removes every value when it comes back up. Save a copy: found.append(list(path)).
Calling height(node.left) and height(node.right) at every node to check balance repeats work. A node at depth d is measured once for every node above it. A version that checks every node before it answers costs about 500,000 steps on a chain of 1,000 nodes, where one pass needs 1,000. Even a version that stops at the first bad node pays about 1.5 million steps on a balanced tree of 100,000.
Return the height from the same call that checks balance.
if node.left is None and node.right is None: return 0 together with if node is None: return 0 gives a leaf and an empty tree the same height. A root with one leaf child then has height 1 + max(0, 0) = 1, and it should be 2. Choose one convention. In this course a leaf is 1 and an empty tree is 0.
Explain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · Two directions
Q1/2 A budget is handed from each node to its children, and every leaf checks what is left. Which way does the information go, and which node is handled first?
Answer: B
A value that is handed down is an argument. A node must receive it before it can pass a changed value on, so the parent comes first.
Q2/2 A node needs the heights of its two children before it can compute its own. Which order of handling fits?
Answer: B
Answers come up in return values. A node can combine them only after both of its calls have finished, which is the post-order.
Checkpoint · Height
Q In this course, what does a recursive height function return for an empty tree and for a single node?
Answer: C
Height counts levels. An empty tree has no levels, and a single node has one. A node is 1 plus the larger height of its two children.
Checkpoint · Balance
Q A tree has a root whose two sides are 3 and 2 levels deep. Does that show the tree is balanced?
Answer: B
Balance is a rule about every node. A node two levels down can have sides of 2 and 0, and the root cannot see that.
Checkpoint · The diameter
Q1/2 The longest path between two nodes in a tree has 5 links, but the left height plus the right height at the root is 4. What does that tell you?
Answer: C
A longest path turns at one node, which may be anywhere. Taking left plus right at every node and keeping the largest finds it.
Q2/2 A node has a left subtree of height 2 and a right subtree of height 3. What does it keep as a candidate for the diameter, and what does it return to its parent?
Answer: C
The best path that turns here joins both sides: 2 plus 3 is 5 links. A parent can extend only one side, so this node returns 1 plus the taller side: 4.
Checkpoint · Paths
Q1/2 A tree has the root 5 and one child, 4. You look for a root-to-leaf path with the total 5. What is the answer?
Answer: B
A root-to-leaf path must end at a leaf. The root is not a leaf, because it has a child. The only path is 5 then 4, which is 9.
Q2/2 An all-paths search adds a node's value to a list, explores both children, and then does something before it returns. What?
Answer: C
The search shares one list among all paths. Removing the value on the way back keeps the list equal to the path from the root to the current node.
Checkpoint · Depth and cost
Q1/2 A recursive function is run in Python on a chain of 3,000 nodes. What is the most likely result?
Answer: B
Each call waits for the one below it, so the depth of the calls is the height of the tree. A chain of 3,000 nodes is far beyond the default limit.
Q2/2 Which is a safe way to compute a height on a chain of 100,000 nodes?
Answer: B
A loop uses a list, not the call stack, so the depth of the tree does not matter. Going backwards through a level-order list handles every node after its children.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.