What is Lowest Common Ancestor
The lowest common ancestor of two nodes is the deepest node that has both of them in its subtree. A node counts as being in its own subtree, so a node can be the ancestor of itself and a descendant.
3 5 1 6 2 0 8 p=5 q=1 ancestor 3
Approach
Search the left side and the right side. If the two targets land in different sides, the current node is the split, and that split is the ancestor.
Values are unique and both targets exist. The picture marks the two targets, then highlights the ancestor the search returns.
Interactive solution
The finished tree is on screen when the page opens. Next and Play start again from the first step. The play controls sit under the tree and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each node is visited once. |
| Call stack | O(h) | The search follows the height. |
Implementation
def find(node, p, q):
if not node or node.val == p or node.val == q:
return node
left, right = find(node.left, p, q), find(node.right, p, q)
if left and right:
return node
return left or right