Problem
Given the root of a binary tree (an ordinary one, not a search tree) and two values p and q that are both in it, return the value of their lowest common ancestor: the deepest node that has both p and q somewhere in its subtree. A node is part of its own subtree, so a node can be its own ancestor.
Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.
Example 1
root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]
Example 2
- Input
- p = 5, q = 1
- Output
- 3
Example 3
- Input
- p = 5, q = 4
- Output
- 5
- Why
- 5 is above 4
Example 4
- Input
- p = 7, q = 4
- Output
- 2
Constraints
2 <= number of nodes <= 10^5-10^9 <= Node.val <= 10^9All values are unique, p != q, and both values exist in the tree.