Menu
CoddyTech

Lowest Common Ancestor of a Binary Tree

You get a binary tree in the array root, in heap order: the root at index 0, the children of index i at 2*i+1 (left) and 2*i+2 (right), and -1 for an empty spot. The values are distinct and follow no order.

Return the value of the lowest common ancestor of p and q, the values of two different nodes: the deepest node whose subtree holds both. A subtree includes its top node, so if q lies below p, the answer is p.

Function

lowestCommonAncestor(root: integer-array, p: integer, q: integer) → integer
rootinteger-array
the binary tree in level order, with -1 for an empty spot
pinteger
the value of one node
qinteger
the value of another node
Returnsinteger
the value of the lowest node whose subtree holds both p and q

Constraints

  • 2 ≤ root.length ≤ 32767
  • Each root[i] is -1 or a value with 0 ≤ root[i] ≤ 104.
  • root[0] is never -1, and the tree has at least two nodes.
  • 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.
  • All values in the tree are distinct, and they follow no order.
  • p and q are the values of two different nodes in the tree, in any order.

Examples

Input
root = [8, 3, 10, 6, 4, 12, 1, -1, -1, 7, 9]p = 6q = 9
Output
3
Explanation
6 is the left child of 3, and 9 sits below 4 on the right of 3, so they meet at 3. Comparing values would point at the root 8: 6 is smaller and 9 larger.
challenge icon

Follow-up

If p or q may be absent, with -1 as the answer, which shortcut in the single pass breaks, and how do you still finish in one traversal?

Reset code
def lowestCommonAncestor(root, p, q):
    # Write code here

Test #1

Test #2

Test #3

Arguments

root = [8, 3, 10, 6, 4, 12, 1, -1, -1, 7, 9]
p = 6
q = 9

Expected Output

3