Menu
CoddyTech

Lowest Common Ancestor of a BST

You get a binary search tree stored in heap order in the array tree: the root is at index 0, the children of index i are at 2*i+1 (left) and 2*i+2 (right), and -1 marks an empty spot. 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 lowestCommonAncestor, which returns the value of the lowest common ancestor of the values p and q, both in the tree: the deepest node that has both in its subtree. A node is part of its own subtree, so if p sits above q, the answer is p.

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
Climbing from 3 and from 15, the first node both reach is 8: 3 is its left child and 15 hangs below 12 on its right. The root 20 is a common ancestor too, but higher.
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 #1

Test #2

Test #3

Arguments

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

Expected Output

8