#9MediumTrees· Ancestor Queries
Lowest Common Ancestor of a Binary Tree
Input format
root: level-order array with `null` for missing children, p: integer, q: integer
Output format
Integer: the value of the lowest common ancestor
Examples
Input: root = [1, 2, 3, 4, 5, 6, 7, null, null, 8, 9], p = 8, q = 9
Output: 5
8 and 9 are the two children of node 5.
Input: root = [1, 2, 3, 4, 5, 6, 7, null, null, 8, 9], p = 8, q = 7
Output: 1
8 is in the left subtree of the root and 7 is in the right subtree, so they only meet at the root.
Input: root = [1, 2, 3, 4, 5, 6, 7, null, null, 8, 9], p = 5, q = 9
Output: 5
5 is an ancestor of 9, and a node counts as its own ancestor.
Constraints
- 2 <= number of nodes <= 10^4
- -10^9 <= Node.val <= 10^9
- All node values are distinct.
- p != q, and both p and q exist in the tree.
Study first
- #trees
- #binary-tree
- #breadth-first-search
- #hash-table
