Lowest Common Ancestor in a Binary Tree
Problem statement
Given a binary tree and two distinct nodes in it, return the value of their lowest common ancestor. A node counts as a descendant of itself.
For this exercise, the runner supplies the target nodes by their unique integer values p and q, and returns the ancestor value instead of a node reference. Both targets exist in the tree. The tree is an ordinary binary tree, not necessarily a binary search tree.
Function
lowestCommonAncestorValue(root: TreeNode, p: int, q: int) → intExamples
Example 1
root = [3,5,1,6,2,0,8,null,null,7,4]p = 5q = 1return = 3The first common ancestor is the root.
Example 2
root = [3,5,1,6,2,0,8,null,null,7,4]p = 5q = 4return = 5A node can be its own descendant, so 5 is the common ancestor.
Example 3
root = [1,2]p = 1q = 2return = 1The root is one of the requested nodes.
Constraints
- The tree contains
2through100000nodes. -1000000000 <= node.val <= 1000000000; all node values are unique.p != qand both target values occur in the tree.