Lowest common ancestor · Medium
A hierarchy debugger compares two distinct node values in a serialized binary tree. It needs the deepest reachable node that contains both in its descendant subtree. A node is also considered its own ancestor.
Return the value of the lowest common ancestor of p and q, or null when either value is not reachable from the root.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "tree": (number|null)[], "p": number, "q": number }.
Fields
- tree is a heap-indexed array: children of index i are 2i+1 and 2i+2. Null or an out-of-range index has no node. Entries below a missing ancestor are unreachable and ignored.
- p and q are integer node values, not array indexes. All non-null values in tree are unique. p may equal q.
Output
Return value
- Return a node value or null.
- If p=q and that node is reachable, return p.
- A value stored below a null ancestor is absent from the actual tree and cannot satisfy the lookup.
Constraints
- 0 <= tree.length <= 100000. Node values are integers in [-1000000000,1000000000].
- This is not a compact breadth-first serialization: missing child slots keep their indexes.
Examples
Example 1
{
"p": 2,
"q": 7,
"tree": [
10,
5,
15,
2,
7
]
}Returns
55 is the deepest shared ancestor.
Example 2
{
"p": 5,
"q": 99,
"tree": [
10,
5,
15
]
}Returns
null99 is absent.
Required complexity
O(n) time and O(n) space or better