DSA Factory
Free Trees lessonsTrees · Stage 5 · Ancestors · Step 3

Steps between two nodes

Count the edges on the path between two nodes of a tree, by going up from each of them to their lowest common ancestor. About 14 minutes.

Up to the meeting point, then down

In a tree there is exactly one route between two nodes. It climbs from the first node to the lowest node that has both below it, their lowest common ancestor, and then descends to the second node.

So the distance is the number of edges from the ancestor down to the first node, plus the number from the ancestor down to the second. If the two nodes are the same, both are zero.

Find the meeting point: the lowest common ancestor.
Add two depths: measured from the ancestor.
In code
steps = depth_p + depth_q
How far is the node 6 from the node 4?
657243018
ancestor
5

The lowest common ancestor of 6 and 4 is 5.

Move 1 of 3

Measure from the ancestor

Use the walk from the last step to get the ancestor. Then write a small helper that finds the depth of a value below a given node, starting at zero for that node.

Calling the helper on the ancestor, rather than on the root, gives the lengths of the two arms of the route directly. If one node is the ancestor of the other, one of the arms has length zero.

Depth below a node: start counting at that node with zero.
One is above the other: one arm has length zero.
In code
depth = 0
node = root
while node.val != v:
    if v < node.val:
    node = node.left
else:
    node = node.right
    depth += 1
Quick check

Node q is the parent of node p. What is the distance between them?

  1. A1, since the ancestor is q and the arms are 0 and 1
  2. B0
  3. C2
Show the answer

1, since the ancestor is q and the arms are 0 and 1. q is the lowest common ancestor, so the arm to q is zero.

Your problem

Distance between two nodes

Given the root of a binary tree whose node values are all different, and two values p and q that both appear in the tree, return the number of edges on the path between the nodes holding p and q. If p and q are equal, the distance is 0.

Example
root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], p = 6, q = 4 → 3

1 ≤ number of nodes ≤ 5,000 · all values are different · p and q are in the tree

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve