A binary tree of invoice line amounts is given in level-order form (a single line of space-separated tokens, null marking a missing child; every non-null node contributes exactly two following tokens for its children).
A left leaf is a node that (a) has no children of its own, and (b) is the left child of its parent (a root with no parent is never a left leaf).
Print the sum of the values of every left leaf in the tree.
Line 1: space-separated level-order tokens describing the binary tree (integers and the token null).
A single integer: the sum of all left-leaf values. If there are none (including an empty tree), print 0.
Example 1
Input
3 9 20 null null 15 7
Expected
24
Explanation
9 is a left leaf (left child of 3, no children). 15 and 7 are children of 20, which is a right child of 3, so 15 (a left leaf of 20) counts but 7 does not. Sum = 9 + 15 = 24.
Example 2
Input
1
Expected
0
Explanation
The root has no parent, so even though it is a leaf it is never a left leaf. Sum = 0.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →