graph TD;
A(10):::blue --- B(3):::blue
A --- C(4)
B --- D(2)
B --- E(1)
classDef hidden display:none
classDef blue fill:#2196f3,stroke:#1565c0,color:#fff;
1
2
3
4
5
6
Input: root =[10,3,4,2,1]Output: 2Explanation:
For the node with value 10: The sum of its descendants is3+4+2+1=10.For the node with value 3: The sum of its descendants is2+1=3.
Example 2:
graph TD;
A(2) --- B(3)
A ~~~ N1:::hidden
B --- C(2)
B ~~~ N2:::hidden
classDef hidden display:none
1
2
3
4
5
Input: root =[2,3,null,2,null]Output: 0Explanation:
No node has a value that is equal to the sum of its descendants.
Example 3:
graph TD;
A(0):::blue
classDef blue fill:#2196f3,stroke:#1565c0,color:#fff;
1
2
3
4
Input: root =[0]Output: 1For the node with value 0: The sum of its descendants is0 since it has no descendants.
Constraints:
The number of nodes in the tree is in the range [1, 105].
For each node, we need to know the sum of all its descendants. We can use postorder DFS to compute the sum for every node efficiently. If a node’s value equals the sum of its descendants, we increment the answer.
classTreeNode {
int val;
TreeNode left, right;
TreeNode(int x) { val = x; }
}
classSolution {
int ans = 0;
privateintdfs(TreeNode node) {
if (node ==null) return 0;
int ls = dfs(node.left), rs = dfs(node.right);
int sum = ls + rs;
if (node.val== sum) ans++;
return sum + node.val;
}
publicintequalToDescendants(TreeNode root) {
ans = 0;
dfs(root);
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
dataclassTreeNode(var `val`: Int, var left: TreeNode? = null, var right: TreeNode? = null)
classSolution {
var ans = 0funequalToDescendants(root: TreeNode?): Int {
ans = 0fundfs(node: TreeNode?): Int {
if (node ==null) return0val ls = dfs(node.left)
val rs = dfs(node.right)
val sum = ls + rs
if (node.`val` == sum) ans++return sum + node.`val`
}
dfs(root)
return ans
}
}