TREE-P5

Lowest common ancestor

Practice 5 of 6Trees and BSTs8 tests

The problem

Given a binary tree and two values p and q that are in it, return the value of their lowest common ancestor: the deepest node that has both in its subtree. A node counts as its own ancestor. All values are different.

tree [3, 5, 1, 6, 2, 0, 8, None, None, 7, 4]
lca(root, 5, 1)  ->  3
lca(root, 7, 4)  ->  2
lca(root, 5, 4)  ->  5

This is any binary tree, not always a search tree, so you cannot steer by comparing values.

The tests write a tree as a level-order list: the values level by level, left to right, with None where a child is missing. So [3, 9, 20, None, None, 15, 7] is 3 with children 9 and 20, where 20 has children 15 and 7. An empty tree is None.

Limits

  • Up to 100,000 nodes, at most 300 levels deep.

Builds on TREE-6 Lowest common ancestor.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

8 tests, not run yet
Test results
#TestResultReads · time
1Split below the rootNot run
2Far apartNot run
3One is above the otherNot run
4The same nodeNot run
5Not a search treeNot run
6Deep in one sideNot run
7Ancestor, not sortedNot run
8100,000 nodesNot run