Problem 256
Sum of Left Leaves
Easy · 10 pts · Tree, Binary Tree, Depth-First Search
Problem
You are given a binary tree. A left leaf is a leaf (a node with no children) that is the left child of its parent. Print the sum of the values of all left leaves, or 0 if there are none. The root alone is not a left leaf, since it has no parent. Traverse the tree, and at each node check whether its left child exists and has no children of its own; if so, add that child's value.
Input
First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child.
Output
Print the sum of the left leaves.
Constraints
1 <= number of nodes <= 1000; -1000 <= value <= 1000
Example input
7 3 9 20 null null 15 7
Example output
24
Explanation
In the tree with root 3, the node 9 is a leaf and the left child of 3, and 15 is a leaf and the left child of 20. The leaf 7 is a right child, so it does not count. The sum is 9 + 15 = 24.