Tree traversal · Medium
A tree inspector lets an operator select two entries that can share the same displayed value. To highlight their smallest shared branch, it needs a stable node identity rather than a value search. The saved tree may contain stale entries beneath removed parents.
Return the heap index of the lowest common ancestor of p and q or null if either selected index is absent or unreachable.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ tree: (integer | null)[], p: integer | null, q: integer | null }
Fields
- tree is a binary tree encoded with heap indexes: root 0; children of i are 2i+1 and 2i+2. This is not compact queue serialization.
- p and q are heap indexes identifying nodes, not values. Each may be null or an integer from 0 through 100000; absent or unreachable indexes are allowed. Values may repeat.
Output
Return value
- Return an integer heap index or null, never the ancestor value. A node is an ancestor of itself.
- Reject null indexes, missing slots and nodes behind a null ancestor. Equal values do not make two different indexes the same node.
Constraints
- 0 <= tree.length <= 100000; each non-null value is an integer from -1000000000 to 1000000000.
- Do not mutate either input array. Sums fit safe JSON integers. Heap indexing bounds the tree height by 17 at this input limit.
Examples
Example 1
{
"p": 3,
"q": 2,
"tree": [
8,
8,
8,
1
]
}Returns
0Example 2
{
"p": 1,
"q": 1,
"tree": [
8,
2,
3
]
}Returns
1Required complexity
O(h) time and O(1) auxiliary space with heap-index parent arithmetic