FastPrepLowest Common Ancestor of a Binary Tree

Lowest Common Ancestor of a Binary Tree

Goldman Sachs logoGoldman Sachs● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

All node values are unique, and both target values occur in the tree. Return the value of the lowest node whose subtree contains both p and q. A node may be 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

The targets lie in different subtrees of node 3.

Constraints

  • The tree contains between 2 and 10000 nodes.
  • All node values are unique signed 32-bit integers.

More Goldman Sachs problems

See Goldman Sachs 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…