Menu
CoddyTech

Lowest Common Ancestor of a BST

You get a binary search tree stored in the array tree in level order, and two values p and q that both appear in it. The root sits at index 0, the children of the node at index i sit at 2*i+1 (left) and 2*i+2 (right), -1 marks an empty spot, and the array may end with extra -1 entries. In a binary search tree, every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger.

Write a function named lowestCommonAncestor that returns the value of the lowest common ancestor of p and q: the deepest node that has both of them in its subtree. A node counts as part of its own subtree, so if p sits above q, the answer is p itself.

Function

lowestCommonAncestor(tree: integer-array, p: integer, q: integer) → integer
treeinteger-array
the binary search tree in level order, with -1 for an empty spot
pinteger
the first value to find
qinteger
the second value to find
Returnsinteger
the value of the deepest node that has both p and q in its subtree

Constraints

  • 1 ≤ tree.length ≤ 32767
  • Each tree[i] is -1 or a value with 0 ≤ tree[i] ≤ 105.
  • tree[0] is never -1, so the tree has at least one node.
  • The array may end with extra -1 entries past the last node.
  • Both children of an empty spot are empty too, and the depth is at most 14.
  • The tree is a valid binary search tree, so all its values are distinct.
  • p and q are values of nodes in the tree. They come in any order and may be equal.

Examples

Input
tree = [20, 8, 31, 3, 12, 25, 40, -1, -1, 10, 15]p = 3q = 15
Output
8
Explanation
The 3 is the left child of 8, and the 15 hangs below 12 on the right of 8. Climbing up from each of them, the first node both reach is 8, so that is the answer; the root 20 is a common ancestor too, but a higher one.

lock icon+12 hidden tests on Submit

challenge icon

Follow-up

What would you change if p or q might be missing from the tree, and the function had to return -1 in that case?

Reset code
def lowestCommonAncestor(tree, p, q):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

tree = [20, 8, 31, 3, 12, 25, 40, -1, -1, 10, 15]
p = 3
q = 15

Expected

8