Problem 601
Sum of Nodes with Even-Valued Grandparent
Medium · 20 pts · Tree, Depth-First Search
Problem
Find the sum of the values of all nodes whose grandparent (the parent of their parent) has an even value. Nodes without a grandparent, such as the root and its children, do not count. If no node qualifies, the answer is 0. Pass the parent and grandparent values down during a depth-first search, so each node can check its grandparent in O(1).
Input
The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.
Output
Print the sum.
Constraints
1 <= number of nodes <= 10000; 1 <= value <= 100
Example input
15 6 7 8 2 7 1 3 9 null 1 4 null null null 5
Example output
18
Explanation
In the tree 6 7 8 2 7 1 3 9 null 1 4 null null null 5, the even-valued grandparents are 6 and 8. Their grandchildren are 2, 7, 1, 3 (under 6) and 5 (under 8), and their sum is 18.