FastPrepLowest Common Ancestor in a Binary Tree

Lowest Common Ancestor in a Binary Tree

Google logoGoogle● MediumNEW GRADPHONE SCREEN
Learn

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

Examples

Example 1

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

Nodes 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 = 5

Node 5 is an ancestor of node 4 and may be the answer itself.

Example 3

root = [1,2]p = 1q = 2return = 1

The root is one of the targets.

Constraints

  • The tree contains between 2 and 2000 nodes.
  • All node values are unique signed 32-bit integers.
  • p != q, and both values occur in the tree.

More Google problems

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