Lowest Common Ancestor of a Binary Search Tree II

Given the root of a binary search tree and two values p and q, return their lowest common ancestor if both values exist in the tree; otherwise return -1. Pattern focus: LCA in BST. This version adds validation so you only accept the answer when both target values are actually present.

Input Format

root = binary tree root, p = first node value, q = second node value

Output Format

LCA value, or -1 if one or both values are absent

Constraints

  • 1 <= number of nodes <= 10^5
  • -10^9 <= node values <= 10^9
  • root, p and q must satisfy the format described in inputFormat.

Examples

Example 1:

Input:

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

Output:

2

Explanation:

Both values exist, and 2 is the ancestor of 4.

Example 2:

Input:

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

Output:

-1

Explanation:

Value 10 does not exist in the tree.

Loading...
Lowest Common Ancestor of a Binary Search Tree…