Binary Tree

Lowest Common Ancestor Visualizer

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.

Both sides answerOne target was found on the left and the other on the right. This node is the first place the two paths meet.
Only one side answersBoth targets are in that subtree, so the ancestor is the answer coming back from that side. If this node is one of the targets, it is the answer immediately.

Values are unique and both targets exist. The picture marks the two targets, then highlights the ancestor the search returns.

Interactive solution

The two targets, then the node where their paths meet
def find(node):
if node is null or node is p or node is q: return node
left = find(node.left)
right = find(node.right)
if left and right: return node
return left or right
Step 0/0 Answer —

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

PieceCostWhy
TimeO(n)Each node is visited once.
Call stackO(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