All practice tasks

Coding (Algo)

Total Selected Tree Values

Tree traversal · Easy

A reporting tool totals signed measurements stored in a binary hierarchy. Users can select only some nodes without removing their children from the hierarchy. Negative values represent adjustments and must not be discarded or converted to absolute values.

Return the signed sum of selected reachable node values and ignore stale entries behind null 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 sum. Empty input or no selected reachable nodes returns zero.
  • Selection excludes a node value but not its descendants. Preserve zero and negative values.

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": [
    10,
    -5,
    2
  ]
}

Returns

-3

Example 2

{
  "tree": [
    1,
    null,
    3,
    99
  ]
}

Returns

4

Required complexity

O(n) time and O(h) auxiliary traversal space excluding the returned output

What this task practices

Total Selected Tree Values is a coding (algo) interview exercise that trains prompt interpretation, explicit assumptions, a concrete response, and a clear explanation of tradeoffs. The catalog marks it as easy difficulty. It focuses on Technical Reasoning, Testing, Validation. The signed-in workspace provides the tools for the round and evaluates the attempt against task-specific criteria. Reference solutions, hidden checks, evaluator instructions, and candidate work remain private.

Sign in to startThe workspace and evaluation open after sign in.