Lowest Common Ancestor in a Binary Tree
Problem statement
Given a nonempty binary tree with unique node values and two values p and q present in the tree, return the value of their lowest common ancestor.
A node is an ancestor of itself. The lowest common ancestor is the deepest node whose subtree contains both target nodes. The targets may be equal. The tree need not be a binary search tree, and neither input tree links nor values may be changed.
The tree is displayed in level order, with null for missing children.
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 targets occur in different root subtrees.
Example 2
root = [3,5,1,6,2,0,8,null,null,7,4]p = 5q = 4return = 5The node holding five is itself an ancestor of the node holding four.
Constraints
- The valid tree contains between
1and20000nodes. - Node values are unique integers in
[-10^9,10^9]. - Both
pandqare existing node values.