Problem 742
Children Sum Property
Easy · 10 pts · Tree, Depth-First Search
Problem
A binary tree satisfies the children sum property if, for every node that has at least one child, the node's value equals the sum of its children's values (a missing child counts as 0). Leaves have no condition. Decide whether the given tree satisfies the property. Visit every node once, with a traversal of your choice, and compare its value with the sum of the values of its existing children.
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 YES if every node satisfies the children sum property, otherwise NO.
Constraints
1 <= number of nodes <= 10000; 0 <= value <= 10^5
Example input
6 10 8 2 3 5 2
Example output
YES
Explanation
In the tree 10 8 2 3 5 2, the root 10 equals 8 + 2, node 8 equals 3 + 5, and node 2 equals its only child 2. All other nodes are leaves, so the answer is YES.