Lowest Common Ancestor of a Binary Tree
Given the root of a binary tree and two distinct nodes p and q that both exist in the tree, return their lowest common ancestor: the deepest node that has both p and q as descendants (a node may be a descendant of itself).
Open official problem prompt ↗Find the deepest node that sits above both target nodes on their root-to-node paths.
Like tracing two people's ancestry back through a family tree until you reach the most recent common grandparent — the first shared name going upward.
- Input
- root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], p = 5, q = 1
- Output
- 3
- Why
- 5 is in the left subtree of 3 and 1 is in the right subtree, so their deepest shared ancestor is the root 3.
The number of nodes is in the range [2, 10^5]-10^9 <= Node.val <= 10^9All Node.val are uniquep != q and both p and q exist in the tree