Binary search tree · Medium
A search-index debugger receives a serialized binary tree. It must detect whether lookups can safely use strict left-smaller and right-larger comparisons. Checking only immediate children misses a corrupted descendant.
Return whether every reachable node satisfies the strict binary-search ordering against all of its ancestors.
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)[] }.
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.
Output
Return value
- Return a boolean. Every value in the left subtree is smaller than its ancestor; every value in the right subtree is larger.
- Reachable duplicate values are invalid. An absent root is a valid empty tree.
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
{
"tree": [
10,
5,
15,
null,
null,
6,
20
]
}Returns
false6 is in the right subtree of 10.
Example 2
{
"tree": [
2,
1,
3
]
}Returns
trueBoth subtree bounds hold.
Required complexity
O(n) time and O(h) traversal space