Skip to content

ORIGINAL CODING QUESTION

Total of left-hand leaf nodes

In a binary chart, a left-hand leaf is a node with no children that is attached as the LEFT child of its parent. The root is never a left-hand leaf, even if it stands alone. Return the sum of values of all left-hand leaves, or 0 if there are none.

Open practice workspace

Original exercise · easy. 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.

Constraints

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

Example 1

Input

3 1 1 2 2 -1 -1 -5 -1 -1

Output

2

Node 1 is a leaf attached on the left; node 2 is attached on the right.

Example 2

Input

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

Output

0

Every node hangs on the right, so no left-hand leaf exists.

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

Being a leaf and being a left child are two separate checks.

Hint 2

Look at each node and inspect only its left child.

Hint 3

Add that left child when it has no children of its own.

Practice this question

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

Open practice workspaceBrowse the question library →