Find the Meeting Point of Two Keys in a Search Tree

Implement lowestCommonInBst

You are given the root of a binary search tree with distinct values and two values p and q that both appear in the tree. Return the value of the lowest node that has both the p-node and the q-node in its subtree; a node counts as being inside its own subtree, so if one of the two nodes is an ancestor of the other, that ancestor is the answer.

The method for general binary trees works here too, but the ordering of a search tree lets you find the answer with a single downward walk, since the keys tell you which side each of them is on.

Example 1:

Input: root = [50,25,75,10,35,60,90,5,15,30,40], p = 15, q = 40

Output: 25

Example 2:

Input: root = [50,25,75,10,35,60,90,5,15,30,40], p = 30, q = 35

Output: 35

Example 3:

Input: root = [50,25,75,10,35,60,90,5,15,30,40], p = 5, q = 90

Output: 50

+ 14 hidden test cases run on Submit.

Constraints:

  • ●2 ≤ number of nodes ≤ 100; all node values are distinct, 0 ≤ node.val ≤ 1000
  • ●The tree is a binary search tree (left subtree smaller, right subtree larger at every node), given by its root node
  • ●p and q are values that both exist in the tree (they may be equal to each other)
  • ●Return the value of the lowest node that has both the p-node and the q-node in its subtree (a node counts as being in its own subtree, so if one is an ancestor of the other, the answer is that ancestor)

root =

[50, 25, 75, 10, 35, 60, 90, 5, 15, 30, 40]

p =

15

q =

40