FastPrepLowest Common Ancestor in a Binary Tree

Lowest Common Ancestor in a Binary Tree

Motive logoMotive● MediumINTERNPHONE SCREEN
Learn

Problem statement

Given a binary tree and two distinct nodes in it, return the value of their lowest common ancestor. A node counts as a descendant of itself.

For this exercise, the runner supplies the target nodes by their unique integer values p and q, and returns the ancestor value instead of a node reference. Both targets exist in the tree. The tree is an ordinary binary tree, not necessarily a binary search tree.

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 first common ancestor is the root.

Example 2

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

A node can be its own descendant, so 5 is the common ancestor.

Example 3

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

The root is one of the requested nodes.

Constraints

  • The tree contains 2 through 100000 nodes.
  • -1000000000 <= node.val <= 1000000000; all node values are unique.
  • p != q and both target values occur in the tree.

More Motive problems

See Motive 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…