Tree traversal · Easy
A tree inspector exports selected entries in structural left-root-right order. The hierarchy is not necessarily sorted by value and duplicate values are valid. Selection affects which values are exported but must not change the traversal order or hide descendants.
Return the selected reachable values in inorder traversal order without sorting by their numeric value.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ tree: (integer | null)[], selected?: boolean[] }
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.
- A null slot removes that node and its entire subtree, even if later descendant slots contain numbers. An omitted selected array selects every node; otherwise it has tree.length booleans. Selection affects contribution only and never removes descendants.
Output
Return value
- Return an array in left subtree then node then right subtree order. Preserve duplicate values.
- An unselected node contributes nothing but both subtrees are still traversed. Empty input returns [].
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
{
"tree": [
5,
9,
1
]
}Returns
[
9,
5,
1
]Example 2
{
"selected": [
false,
true,
true
],
"tree": [
5,
2,
7
]
}Returns
[
2,
7
]Required complexity
O(n) time and O(h) auxiliary traversal space excluding the returned output