Tree traversal · Easy
An inspection tool receives a saved binary hierarchy and a selection mask. It must report how many selected nodes actually belong to the visible tree. Slots left behind a removed parent are stale storage entries and must not inflate the count.
Return the number of selected nodes reachable from the root while continuing through unselected parents.
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 one integer. An empty tree or null root returns zero.
- Count nodes rather than distinct values; two selected nodes with the same value count twice.
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
{
"selected": [
false,
true,
true
],
"tree": [
7,
7,
2
]
}Returns
2Example 2
{
"tree": [
1,
null,
3,
9
]
}Returns
2Required complexity
O(n) time and O(h) auxiliary traversal space excluding the returned output