Problem · Tree

Lowest Common Ancestor Only When Both Targets Exist

Learn this problem
MediumAdobe logoAdobeFULLTIMEONSITE INTERVIEW

Problem statement

Given the root of a binary tree and two target values p and q, return their lowest common ancestor only if nodes with both target values occur in the tree. Otherwise, return null.

The lowest common ancestor is the deepest node whose subtree contains both targets. In the judged representation, every tree value is unique, so p and q identify target nodes by value. The two target values are distinct and either value may be absent.

The returned TreeNode is serialized as the level-order traversal of the subtree rooted at that node.

Function

lowestCommonAncestorIfBoth(root: TreeNode, p: int, q: int) → TreeNode

Examples

Example 1

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

Both targets occur in the subtree rooted at value 5, and no deeper node contains them both.

Example 2

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

The node with value 3 is absent, so the method returns null, serialized here as an empty tree.

Constraints

  • 0 <= number of nodes <= 100000.
  • Every tree value is a unique signed 32-bit integer.
  • p and q are distinct signed 32-bit integers.
  • The input is a finite, acyclic binary tree.

More Adobe problems

drafts saved locally
public TreeNode lowestCommonAncestorIfBoth(TreeNode root, int p, int q) {
    // TODO: return a node only when both targets are present.
}
root[3,5,1,6,2,0,8,null,null,7,4]
p5
q4
expected[5,6,2,null,null,7,4]
checking account