In a binary search tree with distinct values, return the existing node that is the lowest common ancestor of p and q. A node is its own ancestor. The encoded p and q values identify actual nodes in root; returning a new node is invalid.
Example 1
Argument 1 tree: level-order input; omitted children are null.
Input
root = [6,2,8,0,4,7,9,null,null,3,5]
p = 2
q = 8
Output
6
Explanation
2 and 8 are on opposite sides of 6, so the root is their lowest common ancestor.
Example 2
Argument 1 tree: level-order input; omitted children are null.
Input
root = [6,2,8,0,4,7,9,null,null,3,5]
p = 2
q = 5
Output
2
Explanation
2 is an ancestor of 5 and qualifies as its own ancestor.
Example 3
Argument 1 tree: level-order input; omitted children are null.
Input
root = [2,1]
p = 2
q = 1
Output
2
Explanation
Root 2 is one queried node and the other's parent, so return that existing root.
Constraints
2 <= number of nodes <= 10000
p and q exist and have distinct values
Tree is a strict BST
Function contractlowestCommonAncestorArguments: tree, treeNode, treeNode
Loading draft…
SolutionRuns on your device
Loading draft…
Run: 3 examples; Submit: 35 cases, on your device.