Lowest Common Ancestor in a Binary Tree
Problem statement
You are given the root of a binary tree with unique integer values and two values p and q that occur in the tree.
Return the value of their lowest common ancestor: the deepest node whose subtree contains both target nodes. A node is considered an ancestor of itself.
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 = 3Nodes 5 and 1 lie in different subtrees of the root.
Example 2
root = [3,5,1,6,2,0,8,null,null,7,4]p = 5q = 4return = 5Node 5 is an ancestor of node 4 and may be the answer itself.
Example 3
root = [1,2]p = 1q = 2return = 1The root is one of the targets.
Constraints
- The tree contains between
2and2000nodes. - All node values are unique signed 32-bit integers.
p != q, and both values occur in the tree.