Example 1
- Input
- root = [3,5,1,6,2,0,8,null,null,7,4], p = node 5, q = node 1
- Output
- node 3
The targets are in different root subtrees, so neither subtree contains both. Their first shared ancestor is the original root object 3.
Return the deepest node that is an ancestor of both given nodes in an arbitrary binary tree. A node counts as its own ancestor, and the result must be the original node object.
Given the root of a binary tree and two distinct nodes p and q that exist in it, return their lowest common ancestor. The lowest common ancestor is the deepest node whose subtree contains both targets.
A node is a descendant of itself, so the answer may be p or q. This tree has no binary-search ordering: compare node identity, not values or left/right value ranges.
2 <= number of nodes <= 10^5-10^9 <= Node.val <= 10^9; node values are unique.p != q; both node objects exist in the tree.The targets are in different root subtrees, so neither subtree contains both. Their first shared ancestor is the original root object 3.
In this minimum-size tree, the root is itself p and also the parent of q. A target may be the answer.
The path from 4 goes through 2 and then 5. Since 5 counts as its own ancestor, the lowest shared ancestor is 5, not 3.
Two nodes share the upper portion of their paths from the root. Walking upward from 5 and 1 in Example 1 reaches 3 first on both paths. Remember each node’s parent, mark the ancestors of p, then climb from q until its path first touches those marks. That first intersection is deeper than every later shared ancestor.
Reveal Iterative Parent Map: intuition, complexity, and code
A parent map turns a rooted structure into upward paths. Their first intersection from either target gives the deepest shared ancestor without relying on value ordering.