Lowest Common Ancestor of a Binary Tree
Return the value of the lowest common ancestor of nodes with values p and q Example: [3,5,1,6,2,0,8,null,null,7,4], p=5, q=1 => 3
I return the node itself when I find it, and null when I do not. The first node that hears back from both sides is the answer.
Examples
You write
lowest_common_ancestor(root: Optional[TreeNode], p: int, q: int)
Example 1
- Input
- root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
- returns
- 3
Example 2
- Input
- root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
- returns
- 5
The pattern behind it
BFS & DFS
I reach for it when
- You walk a grid, a graph or a tree and visit each cell once.
- The word shortest appears and every step costs the same.
Say this before you type. Say why breadth or depth fits, and exactly when a cell counts as visited.
All 52 BFS & DFS problemsTrees
I reach for it when
- Each node has children, and the answer depends on the subtrees.
- The statement says depth, height, ancestor or path.
Say this before you type. Say what a call returns for an empty tree, and what it returns for a node.
All 22 Trees problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.
Each locked part opens in the editor once the part before it passes.
Prep guides that list this problem
Our company tags come from public interview write-ups. None of these is a confirmed question.