[LeetCode] Count Nodes Equal to Sum of Descendants

1973. Count Nodes Equal to Sum of Descendants

Given the root of a binary tree, return the number of nodes where the value of the node is equal to the sum of the values of its descendants.

A descendant of a node x is any node that is on the path from node x to some leaf node. The sum is considered to be 0 if the node has no descendants.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
int res = 0;
long long helper(TreeNode* node) {
if(!node) return 0;
long long sum = helper(node->left) + helper(node->right);
if(sum == node->val) res++;
return sum + node->val;
}
public:
int equalToDescendants(TreeNode* root) {
helper(root);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/11/PS/LeetCode/count-nodes-equal-to-sum-of-descendants/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.