FastPrepLowest Common Ancestor in a Binary Tree

Lowest Common Ancestor in a Binary Tree

Apple logoApple● MediumNEW GRADPHONE SCREEN
Learn

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) → int

Examples

Example 1

root = [3,5,1,6,2,0,8,null,null,7,4]p = 5q = 1return = 3

The targets occur in different root subtrees.

Example 2

root = [3,5,1,6,2,0,8,null,null,7,4]p = 5q = 4return = 5

The node holding five is itself an ancestor of the node holding four.

Constraints

  • The valid tree contains between 1 and 20000 nodes.
  • Node values are unique integers in [-10^9,10^9].
  • Both p and q are existing node values.

More Apple problems

See Apple hiring insights
public int lowestCommonAncestorValue(TreeNode root, int p, int q) {
    // Write your solution here.
}
root[3,5,1,6,2,0,8,null,null,7,4]
p5
q1
expected3
Checking account…