Lowest Common Ancestor in Ordered and Unordered Trees
Problem statement
You are given the root root of a binary tree, two distinct node values p and q, and a boolean isBst. Return the value of their lowest common ancestor.
A common ancestor has both target nodes in its subtree, allowing a node to be its own descendant. The lowest common ancestor is the common ancestor furthest from the root.
- If
isBstistrue, the input is a strict binary search tree: every value in a node's left subtree is smaller and every value in its right subtree is larger. - If
isBstisfalse, the input is an ordinary binary tree with no ordering guarantee. Its values must not be used to choose a search direction.
For this exercise, assume all node values are unique and both target values occur in the tree. The input uses level-order tree serialization with null for absent children.
What the interview report shared
The initial task used BST ordering. The follow-up removed that ordering and called for a general binary-tree solution using postorder traversal.
Function
lowestCommonAncestor(root: TreeNode, p: int, q: int, isBst: boolean) → intExamples
Example 1
root = [6,2,8,0,4,7,9,null,null,3,5]p = 2q = 8isBst = truereturn = 6The targets lie on opposite sides of the root, so their lowest common ancestor is 6.
Example 2
root = [6,2,8,0,4,7,9,null,null,3,5]p = 2q = 4isBst = truereturn = 2Node 2 is an ancestor of node 4 and is also its own descendant.
Example 3
root = [2,1]p = 2q = 1isBst = truereturn = 2The root is one of the targets and contains the other target below it.
Example 4
root = [3,5,1,6,2,0,8,null,null,7,4]p = 5q = 1isBst = falsereturn = 3The ordinary tree has one target in each root subtree; no BST ordering may be assumed.
Example 5
root = [3,5,1,6,2,0,8,null,null,7,4]p = 5q = 4isBst = falsereturn = 5Node 5 is itself a target and is an ancestor of node 4.
Example 6
root = [1,2]p = 1q = 2isBst = falsereturn = 1The same self-descendant rule applies to an ordinary binary tree.
Constraints
- For this exercise, assume the finite, acyclic tree contains
2through10^5nodes. -10^9 <= node.val <= 10^9, with all values unique.p != q, and both values occur in the tree.isBstistrueonly when the entire tree satisfies the strict BST ordering rule;falsemakes no ordering guarantee.