Instructions
You are given the root of a binary search tree (BST) and two of its nodes, p and q. Return their lowest common ancestor.
A node a is an ancestor of a node b if you can reach b by starting at a and only moving down to children. A node counts as an ancestor of itself. The lowest common ancestor of p and q is the node that is an ancestor of both and is the farthest from the root.
In a BST, every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger. All values in the tree are different.
Note
pandqcan be the same node. Then the answer is that node.- If
pis an ancestor ofq, the answer ispitself.
How the input is shown
A tree is shown as a list of values in level order: row by row from the top, and left to right in each row. null means "no child here", and nulls at the end are left out. For example, [4, 2, 7, null, 3] is a root 4 with left child 2 and right child 7, and 2 has only a right child, 3.
p and q are shown as values, but your function receives the nodes of the tree that hold these values (TreeNode objects with fields val, left, right). Return a node of the tree. The judge reads the val of the node you return and compares it with the expected value.
Hint: compare p.val and q.val with the current node. If both are smaller, the answer is in the left subtree. If both are larger, it is in the right subtree. Otherwise the current node is the answer.
Examples
Example 1
- Input:
- [40,20,60,10,30,50,70], 10, 30
- Output:
- 20
10 is the left child of 20 and 30 is the right child of 20. Node 20 is an ancestor of both, and no lower node is.
Example 2
- Input:
- [12,5,18,2,9,15,25,null,null,7], 5, 7
- Output:
- 5
7 is the left child of 9, and 9 is the right child of 5. So 5 is an ancestor of 7. A node is also its own ancestor, so the answer is 5.
Example 3
- Input:
- [8,3,11], 11, 11
- Output:
- 11
p and q are the same node, 11. The lowest node that is an ancestor of both is 11 itself.
Constraints
- The number of nodes is between
1and40. 1 <= Node.val <= 999- All values are different, and the tree is a valid BST.
pandqare nodes of the tree (they can be the same node).
3 examples run when you press Run. Submit checks every hidden test too.
- Input:
- [40,20,60,10,30,50,70], 10, 30
- Expected:
- 20
- Input:
- [12,5,18,2,9,15,25,null,null,7], 5, 7
- Expected:
- 5
- Input:
- [8,3,11], 11, 11
- Expected:
- 11
Run checks your code against the 3 examples. Submit checks it against all 153 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.