Ctrl K

Node Worth Its Descendants

Medium
You are given the 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.
Example 1
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.

Example 2
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.

Example 3
root=tree_node([0, 0]) → 2

Both nodes have a descendant sum of 0, equal to their value.

Constraints
  • The tree has between 1 and 10⁵ nodes
  • 0 ≤ Node.val ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsIs It a Search Tree? MediumTwo Mixed-Up Nodes MediumAll Leaf Paths With a Given Total MediumTree Into a Right Chain MediumDigit Branch Totals Medium
loading Python…
Input
root=tree_node([12, 5, 1, 3, 2, None, 1])
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 105 tests on the server, hidden ones included.