Data Structures Β· Visualization
Binary Tree: Lowest Common Ancestor
Binary Tree
The lowest common ancestor (LCA) of two nodes is the deepest node that has both as descendants (a node can be its own ancestor). Time: O(n) for a general binary tree (O(h) for a BST using ordering). Space: O(h) recursion stack.
Big-O: Traversals visit every node exactly once: O(n).
Binary Tree: Lowest Common Ancestor
Binary TreeThe lowest common ancestor (LCA) of two nodes is the deepest node that has both as descendants (a node can be its own ancestor). For a general binary tree, it's found by searching both subtrees and combining the results.
How Lowest Common Ancestor Works
- If the current node is null, or matches either target node, return the current node.
- Recursively search the left subtree for either target.
- Recursively search the right subtree for either target.
- If both the left and right searches return a non-null result, the current node is the LCA.
- Otherwise, propagate up whichever side returned a non-null result.
Lowest Common Ancestor Worked Example
Input: Find LCA of nodes 5 and 1 in tree rooted at 3, with children (5,1) under root, 5 has children (6,2)
- At root 3: search left (subtree rooted at 5) and right (subtree rooted at 1)
- Left search finds 5 itself (matches target) β returns 5
- Right search finds 1 itself (matches target) β returns 1
- Both sides non-null β root 3 is the LCA
Output: LCA(5, 1) = 3
Press βΆ Run to watch it step by step.
def inorder(n):
if not n:
return
inorder(n.left) # left
print(n.val, end=" ") # node
inorder(n.right) # right
# left -> root -> right
# (sorted order for a BST)
# example: lcaBehind the Scenes Execution
Press βΆ Run in the visualizer β the call stack, registers and memory will replay here in sync with the code, line by line.
Lowest Common Ancestor Time & Space Complexity
When to Use Lowest Common Ancestor
- Finding relationship distance in family/org-chart trees
- Network routing (common ancestor router)
- Version control merge-base computation
Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action β visualize the algorithms that operate on these structures, or take a guided course.