Skip to content

ORIGINAL CODING QUESTION

Downward chains with a target total

A downward chain starts at any node of a binary chart and follows child links downward to the same node or one of its descendants, so a single node is a chain on its own. Count the chains whose node values add up to exactly the target. Values may be negative or zero, so chains can overlap and still qualify.

Open practice workspace

Original exercise · hard. Editorial role relevance does not imply a company has asked this question.

Input and output

n, then n triples (value,leftChild,rightChild). Node 0 is the root; a missing child is written as -1. Then the target.

Constraints

1 ≤ n ≤ 200; -100 ≤ value ≤ 100; the triples form one connected binary tree and every child ID is larger than its parent ID. -1000 ≤ target ≤ 1000.

Example 1

Input

7 1 1 2 2 3 4 3 5 6 -1 -1 -1 1 -1 -1 0 -1 -1 3 -1 -1 3

Output

5

Chains 1→2, 2→1, 3 alone, 3→0 and the bottom 3 alone each total 3.

Example 2

Input

3 0 1 -1 0 2 -1 0 -1 -1 0

Output

6

Every one of the six downward chains in a zero-valued chain of three totals 0.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

Each chain is fixed by its lowest node and how far up it reaches.

Hint 2

With root-to-node running sums, a chain sum is the difference of two running sums along one root path.

Hint 3

During a depth-first walk keep a count of running sums on the current root path, and remove a sum when leaving its node.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →