Skip to content

Commit 1eef7f6

Browse files
Sync LeetCode submission Runtime - 3 ms (97.01%), Memory - 25.1 MB (41.18%)
1 parent 2eaed88 commit 1eef7f6

2 files changed

Lines changed: 68 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<p>Given the <code>root</code> of a binary tree, return the most frequent <strong>subtree sum</strong>. If there is a tie, return all the values with the highest frequency in any order.</p>
2+
3+
<p>The <strong>subtree sum</strong> of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/24/freq1-tree.jpg" style="width: 207px; height: 183px;" />
8+
<pre>
9+
<strong>Input:</strong> root = [5,2,-3]
10+
<strong>Output:</strong> [2,-3,4]
11+
</pre>
12+
13+
<p><strong class="example">Example 2:</strong></p>
14+
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/24/freq2-tree.jpg" style="width: 207px; height: 183px;" />
15+
<pre>
16+
<strong>Input:</strong> root = [5,2,-5]
17+
<strong>Output:</strong> [2]
18+
</pre>
19+
20+
<p>&nbsp;</p>
21+
<p><strong>Constraints:</strong></p>
22+
23+
<ul>
24+
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
25+
<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
26+
</ul>
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
int mostFreq;
14+
unordered_map<int, int> freq;
15+
16+
int dfs(TreeNode* root) {
17+
if (root == nullptr) return 0;
18+
19+
int leftSum = dfs(root->left);
20+
int rightSum = dfs(root->right);
21+
int sum = root->val + leftSum + rightSum;
22+
23+
freq[sum]++;
24+
mostFreq = max(mostFreq, freq[sum]);
25+
26+
return sum;
27+
}
28+
29+
public:
30+
vector<int> findFrequentTreeSum(TreeNode* root) {
31+
mostFreq = 0;
32+
dfs(root);
33+
34+
vector<int> res;
35+
for (auto i : freq) {
36+
if (i.second == mostFreq) res.push_back(i.first);
37+
}
38+
39+
return res;
40+
}
41+
};
42+

0 commit comments

Comments
 (0)