Binary Trees Depth first: return a value up
362. Children Sum Property
You are given root, the root node of a binary tree. Return true if the tree has the children sum
property, and false otherwise.
A tree has the property when every node with at least one child holds a value equal to the sum of its children's values. A missing child counts as 0, so a node with a single child must equal that child. A leaf has no children and always passes. An empty tree has the property.
The examples write a tree level by level, from left to right, with null where a child is missing. So
root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The
missing children after the last node are left out.
Example 1
Input: root = [10, 4, 6, 1, 3, null, 6, null, null, 2, 1]
trueExplanation: 10 = 4 + 6, 4 = 1 + 3 and 3 = 2 + 1. Node 6 has only a right child, 6, and its missing left child counts as 0. The leaves 1, 6, 2 and 1 have nothing to check.
Example 2
Input: root = [0, -5, 5, -5, 0, 2, 3]
trueExplanation: 0 = −5 + 5, −5 = −5 + 0 and 5 = 2 + 3. Values can be negative or zero.
Example 3
Input: root = [12, 7, 5, 3, 4, 5, null, null, null, 1, 2]
falseExplanation: The root, 7 and 5 all pass. But node 4 has children 1 and 2, which add up to 3.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109- The tree has at most 1000 levels.
Clarifying questions
What you would ask an interviewer before writing any code.