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.
root = binary tree root, p = first node value, q = second node value
LCA value, or -1 if one or both values are absent
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.