root of a binary tree. The descendants of a node are all nodes below it: its children, their children, and so on. A node with no descendants has a descendant sum of 0.
Count the nodes whose value equals the sum of the values of all their descendants.root=tree_node([12, 5, 1, 3, 2, None, 1]) → 3
The root's descendants sum to 5 + 1 + 3 + 2 + 1 = 12, a match. Node 5 has descendants 3 and 2, summing to 5, a match. Node 1 has a single descendant 1, also a match. The leaves 3, 2 and 1 are not zero. The answer is 3.
root=tree_node([7, None, 4, None, 2]) → 0
The descendants of 7 sum to 6, those of 4 sum to 2, and the leaf 2 has a sum of 0. No matches.
root=tree_node([0, 0]) → 2
Both nodes have a descendant sum of 0, equal to their value.
Node.val ≤ 10⁵root=tree_node([12, 5, 1, 3, 2, None, 1])
3
Run checks the first 3 tests in your browser. Submit checks all 105 tests on the server, hidden ones included.