Find the lowest common ancestor in a search tree, in any tree and with parent links, and use it for distances between nodes.
You are building the escalation tool of a ride-hailing app. Agents sit in a chart: each agent has a manager above them, and the top manager has none. Two agents disagree about one trip.
The tool must find the lowest manager who is above both of them. If one of the two agents manages the other, that agent decides. Then your team lead asks for more.
All of them start from the same question: where do the paths from the top to the two agents part?
Two hikers set out from two huts on a mountain, and both walk down. Their trails join at some place, and from there to the valley they walk the same path. The first place where their trails join is the answer to a question that is easy to ask: where can they meet?
Here is how this maps to a tree. The valley is the top of the tree, each hut is a node, and each trail is the path of ancestors from that node up to the top. The place where the two trails join is the lowest common ancestor.
Two hikers walk down by different trails, and the trails join at some place. That first place is the lowest common ancestor of the two huts.
An ancestor of a node is any node on the path from the top down to it, the node itself included. A common ancestor of two nodes is an ancestor of both. The lowest common ancestor is the common ancestor that is furthest from the top. All common ancestors lie on one chain from the top, so the lowest one is the last of the chain.
We use depth as before: the top has depth 0, and a node has the depth of its parent plus 1. The lowest common ancestor is never deeper than either node.
Step by step: A tree in memory. The animated player loads in your browser.
Predict what happens
Q Two nodes are on the same path from the top, and one is the parent of the other. What is their lowest common ancestor?
Answer: B
A node counts as its own ancestor. The upper node is above the lower one and above itself, so it is the lowest node that is above both.
We use one search tree for the first examples. The numbers are only ids.
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13The path from the top to the id 4 is 8, 3, 6, 4. The path to the id 7 is 8, 3, 6, 7. They share 8, 3 and 6, and part after 6. So the lowest common ancestor of 4 and 7 is 6.
You do not need both paths. The order tells you where each id is. If both ids are smaller than the node, they are both on its left, so go left. If both are larger, go right.
Otherwise stop: the ids part here, or one of them is this node.
| Round | Node | Both ids smaller? | Both ids larger? | Move |
|---|---|---|---|---|
| 1 | 8 | yes | no | left |
| 2 | 3 | no | yes | right |
| 3 | 6 | no | no | stop: the answer is 6 |
def lowest_common(root, p, q):
node = root
while True:
if p < node.value and q < node.value:
node = node.left
elif p > node.value and q > node.value:
node = node.right
else:
return nodeThe walk reads one path: the height, and 3 nodes here.
Step by step: The path from the top to 4. The animated player loads in your browser.
Step by step: The path from the top to 7. The animated player loads in your browser.
Exercise · Predict the output: Where does the walk stop?. The code builds a search tree from the ids in this order, then runs the walk for p = 13 and q = 14. It prints each node it visits, then the answer. What does it print?
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(node, value):
if node is None:
return Node(value)
if value < node.value:
node.left = insert(node.left, value)
else:
node.right = insert(node.right, value)
return node
root = None
for v in [8, 3, 10, 1, 6, 14, 4, 7, 13]:
root = insert(root, v)
p, q = 13, 14
node = root
visited = []
while True:
visited.append(node.value)
if p < node.value and q < node.value:
node = node.left
elif p > node.value and q > node.value:
node = node.right
else:
break
print(*visited, "->", node.value)In a search tree, the walk goes left when both ids are smaller, right when both are larger, and stops when they part. It reads one path.
Exercise · Break it: Find the pair this walk gets wrong. This function finds the lowest common ancestor in a search tree built by inserting the ids in the order you give. It compares with "smaller or equal" and "larger or equal". Find ids and a pair p and q that are both in the tree where it gives the wrong answer.
def lowest_common(root, p, q):
node = root
while node:
if p <= node.value and q <= node.value:
node = node.left
elif p >= node.value and q >= node.value:
node = node.right
else:
return node.valuePredict what happens
Q On the tree above, where does the walk stop for the ids 1 and 13?
Answer: C
At 8, the id 1 is smaller and the id 13 is larger. They are not on the same side, so the walk stops at the top. The path to 1 is 8, 3, 1 and the path to 13 is 8, 10, 14, 13.
Take a chart whose ids are in no order. The top is 31, with 12 and 47 under it. Under 12 are 5 and 28, and under 28 are 19 and 36. Under 47 is 60, and under 60 is 8.
You ask for the lowest common manager of 19 and 36.
An id being larger than the node says nothing here, so the walk cannot pick a side. Give each person a count: how many of the two wanted people are in their side, the person included. A person adds their count to their manager.
To handle every person after the people under them, list the chart with a stack so that every manager comes before the people under them. Then go through the list backwards.
| Round | Person taken | Count when reached | What happens |
|---|---|---|---|
| 1 | 5 | 0 | adds 0 to 12 |
| 2 | 19 | 1 | adds 1 to 28 |
| 3 | 36 | 1 | adds 1 to 28 |
| 4 | 28 | 2 | stop: the answer is 28 |
All common managers lie on one chain from the top. The lowest of them has the smallest side that holds both, and going backwards reaches it first. A wanted person counts itself, so a manager of the other wanted person has the count 2 when its side is added.
With ids in no order, each person counts the wanted people in their side. Going backwards, the first count of two is the answer.
Sometimes each node knows only its parent. Take hubs 0 to 9, where the top is 0 and hubs 1 and 2 are under it. Hubs 3 and 4 are under 1, hub 5 is under 2, and hubs 6 and 7 are under 4. Hub 8 is under 5, and hub 9 is under 7.
You ask for the lowest hub that 9 and 5 share.
You cannot walk down from the top, but you can climb. Count the depth of each hub: hub 9 has 4 links to the top and hub 5 has 2. Lift the lower hub, 9, until the depths are equal. Then lift both together until they are the same hub.
| Stage | p | q | Depth of p | Depth of q |
|---|---|---|---|---|
| start | 9 | 5 | 4 | 2 |
| lift p | 7 | 5 | 3 | 2 |
| lift p | 4 | 5 | 2 | 2 |
| lift both | 1 | 2 | 1 | 1 |
| lift both | 0 | 0 | 0 | 0 |
The answer is hub 0. Equal depths matter: two climbs of different length reach a shared hub at different steps, and so they can pass each other. The cost is a few climbs of the height, and the memory is a few variables.
Step by step: The path from the top to 13. The animated player loads in your browser.
Exercise · Find the bug: The climb that stops one node low. The tree is kept as two lists: parent[i] and depth[i]. This function lifts the deeper node until the depths match, then lifts both together, and should return the lowest common ancestor. For some pairs it returns a node that is too low. Which line is wrong?
def lowest_common(parent, depth, p, q):
while depth[p] > depth[q]:
p = parent[p]
while depth[q] > depth[p]:
q = parent[q]
while parent[p] != parent[q]:
p = parent[p]
q = parent[q]
return pPredict what happens
Q Two hubs have the depths 5 and 2. How many times is the lower hub lifted before the two are lifted together?
Answer: B
The depths must be equal first. The lower hub is lifted by the difference, 5 - 2 = 3 times. After that both are at depth 2.
The path between two nodes goes up to their lowest common ancestor and down again. So its length is the depth of the first, plus the depth of the second, minus twice the depth of the ancestor.
On the search tree above, the ids 4 and 13 have depth 3 each. Their lowest common ancestor is 8, at depth 0. The distance is 3 + 3 - 0 = 6. The ids 4 and 7 have depth 3 each, and their ancestor 6 has depth 2, so the distance is 3 + 3 - 4 = 2.
Adding the two depths alone counts the links above the ancestor twice. For 4 and 7 it would give 6, and the right answer is 2.
The distance between two nodes is the depth of each, minus twice the depth of their lowest common ancestor. The path goes up and down.
Exercise · Put it in order: The distance by lifting. The tree is kept as two lists: parent[i] is the parent of node i (-1 for the root), and depth[i] is its depth. Arrange the lines into a function that returns the number of links between nodes p and q: lift the deeper one until the depths match, then lift both together until they meet.
def distance(parent, depth, p, q):
steps = 0
while depth[p] > depth[q]:
p = parent[p]
steps += 1
while depth[q] > depth[p]:
q = parent[q]
steps += 1
while p != q:
p, q = parent[p], parent[q]
steps += 2
return steps
while depth[p] != depth[q]:Predict what happens
Q On the search tree above, the ids 1 and 6 are at depth 2, and their lowest common ancestor 3 is at depth 1. How many links are between 1 and 6?
Answer: B
The distance is 2 + 2 - 2 x 1 = 2. The path goes up from 1 to 3, and down to 6.
Now a different question: which nodes are exactly k links from a given node? The path may go up as well as down, so each node needs its parent.
Start with a ring that holds only the given node. In each round, put the children and the parent of every node of the ring into the next ring. Skip any node that was already seen.
On the search tree above, take the id 3 and k = 2. The ring starts as 3. After one round it is 1, 6 and 8: the two children and the parent.
After the second round it is 4, 7 and 10, and these are the answer. The ids 4 and 7 are below 6, and 10 is the other child of the parent 8.
The seen marks matter. The parent of 6 is 3, and 3 is already seen, so the ring does not step back. Each node enters one ring, so the whole walk takes n steps.
One more question has the same idea for a group. Take the tree with 8, 3 and 10 on top, 1 and 6 under 3, and 4 and 7 under 6.
The deepest nodes are 4 and 7. The smallest node above both is 6.
Mark the deepest nodes with 1. Then go through the list from the bottom, adding each count to the parent. The first node whose count equals the number of deepest nodes is the answer. It is the same count as for two nodes.
All costs follow the height h or the number of nodes n. For 100,000 nodes, h is about 17 on a balanced tree and 100,000 on a chain.
| Operation | Balanced tree | Chain | What sets the cost |
|---|---|---|---|
| Search for an id | About 17 steps | n | One path from the top |
| Height of the tree | About 17 levels | n | The shape: balanced or a chain |
| Insert an id | About 17 steps | n | One path down, then one link |
| Delete an id | About 17 steps | n | Finding the node, then maybe the next id in order |
| Walk every node | n | n | Each node is taken once |
| Lowest common ancestor in a search tree | About 17 steps | n | One path, using the order |
| Lowest common ancestor in any tree | n | n | Each node is listed and counted once |
| Lowest common ancestor with parent links | About 4h at most | About 4n at most | Two depth climbs, then two lifts |
| Distance between two nodes | The same as the ancestor | n | Two depths and one ancestor |
| Every node k links away | n | n | Each node enters one ring |
| Smallest node over the deepest nodes | n | n | One count for each node |
The order of a search tree is what makes the first row cheap. Without it, you must look at every node, or climb from the nodes you were given.
Use the sandbox to see two paths part. Each search shows the path from the top to one id.
Try these five, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now build the chart behind a support tool. The lab gives you an OrgChart class. You add the top person with add_root and everyone else with add_report, naming the manager. Then you ask depth, lowest_common, distance and is_above.
The point is that each person records a manager and a depth when added. Then no question has to walk to the top. A question lifts the deeper person to the depth of the other, then lifts both together. The distance and is_above reuse the depths.
Three things to take care over:
is_above. A refused addition changes nothing.lowest_common of a person and their manager is the manager, and lowest_common of a person with themselves is that person.Each test creates a new, empty chart, 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.
Use the lowest common ancestor when the question is about the lowest node that is above two nodes, the distance between them, or a group of nodes. In a search tree, use the order. When nodes know their parents, lift by depth. In any other tree, count what each side holds.
Use a loop for every walk. A tree can be a chain of 100,000 nodes, and recursion would be 100,000 calls deep.
If you must answer many pairs on the same tree, one walk for each pair costs n each. Keep the depths and parents, or use binary lifting, so that each pair costs about log n. If the nodes may be in different trees, the climbs reach the top without meeting, so check for that.
If you need the nodes that lie between two nodes rather than their meeting point, use the paths, not only the ancestor.
def lowest_common(values, left, right, p, q):
low, high = min(p, q), max(p, q)
node = 0
while True:
v = values[node]
if low < v < high:
return v
node = right[node] if v <= low else left[node]When one id is an ancestor of the other, the strict test misses it. On the tree above with the ids 3 and 7, the walk goes past 3 and returns 6, and the answer is 3. Stop when the node is not strictly on one side: that includes equal to one of the ids.
A common mistake in a search tree: stopping only when a node is strictly between the two ids. That misses an id that is above the other.
below[parent[node]] += below[node] + (1 if node_is_wanted else 0)
if below[node] == 2:
return nodeThis counts only the wanted people below a person, not the person. When one wanted person manages the other, that manager has only 1 below it. On the chart with the top 31 and the ids 12 and 19, this returns 31 and not 12. Start each person's count at 1 when they are wanted.
while p != q:
p = parents[p]
q = parents[q]Take the hubs 0 to 9 above, with p = 9 and q = 5. The loop does not stop: one climb passes the top while the other has not reached it. Count the depths and lift the lower hub first.
for node in ring:
grown += [left[node], right[node], parent[node]]The parent of a child is the node it came from, so the ring steps back. On the search tree above with the id 3 and k = 2, the answer lists the id 3 three times, with 4, 7 and 10 also present. Mark each node when it joins a ring, and skip marked nodes.
def lowest(node, p, q):
if node is None or node.value in (p, q):
return node
a = lowest(node.left, p, q)
b = lowest(node.right, p, q)
return node if a and b else a or bWith both ids at the bottom of a chain of 2,000 nodes this fails in Python with a RecursionError, because Python allows about 1,000 nested calls. List the nodes with a stack and count going backwards, as above, and a chain of 100,000 nodes is no problem.
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 · The idea and the search tree
Q1/3 What is the lowest common ancestor of two nodes?
Answer: C
All common ancestors lie on one chain from the top. The lowest common ancestor is the one furthest from the top.
Q2/3 In a search tree with the ids 8, 3, 10, 1, 6, 14, 4, 7 and 13, where does the walk stop for the ids 3 and 7?
Answer: C
At 8 both ids are smaller, so the walk goes left. At 3, the id 3 is not smaller than 3, so the ids are not both on one side. The walk stops, and the answer is 3.
Q3/3 Why does the walk that goes left or right by comparing ids fail on a tree whose ids are in no order?
Answer: B
The walk relies on smaller ids being on the left and larger on the right. Without that order, you must ask each side what it holds.
Checkpoint · Counting and parent links
Q1/3 A chart is listed so that every manager comes before the people under them, and read backwards. A person's count starts at 1 when the person is wanted. When does the walk stop?
Answer: C
A count of 2 means both wanted people are in that person's side. Going backwards reaches the lowest such person first.
Q2/3 Each hub knows only its parent. Hub p has depth 4 and hub q has depth 2. What is done first?
Answer: B
The depths must be equal before the joint lift. The lower hub, p, is lifted by the difference, 4 - 2 = 2 times.
Q3/3 What goes wrong when two hubs at different depths are lifted together one step at a time?
Answer: B
A shared hub is reached at different steps by the two climbs, so they do not stand on it together. Equal depths reach it at the same step.
Checkpoint · Distance and rings
Q1/3 The ids 4 and 7 are at depth 3, and their lowest common ancestor 6 is at depth 2. How many links are between 4 and 7?
Answer: C
The distance is 3 + 3 - 2 x 2 = 2. The path goes up from 4 to 6, and down to 7.
Q2/3 To find every node exactly k links from a node, a ring is grown one link at a time. Why must each node be marked when it joins a ring?
Answer: B
Each node is a neighbour of the nodes it came from. A seen mark keeps every node in one ring, so the nodes in the k-th ring are exactly k links away.
Q3/3 On the search tree with the ids 8, 3, 10, 1, 6, 14, 4, 7 and 13, which nodes are exactly 2 links from the id 3?
Answer: B
After one round the ring is 1, 6 and 8. After the second round it is the children of 6, which are 4 and 7, and the other child of 8, which is 10.
Checkpoint · Limits
Q A tree is a chain of 100,000 nodes. Which way to find the lowest common ancestor is safe?
Answer: B
A recursive walk would be 100,000 calls deep, and Python allows about 1,000. A loop has no such limit.
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.