|
| 1 | +/* |
| 2 | + * @lc app=leetcode.cn id=508 lang=cpp |
| 3 | + * |
| 4 | + * [508] 出现次数最多的子树元素和 |
| 5 | + */ |
| 6 | + |
| 7 | +// @lc code=start |
| 8 | +/** |
| 9 | + * Definition for a binary tree node. |
| 10 | + * struct TreeNode { |
| 11 | + * int val; |
| 12 | + * TreeNode *left; |
| 13 | + * TreeNode *right; |
| 14 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 15 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 16 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 17 | + * }; |
| 18 | + */ |
| 19 | +class Solution { |
| 20 | +public: |
| 21 | + vector<int> findFrequentTreeSum(TreeNode* root) { |
| 22 | + int _ = getSum(root); |
| 23 | + int max_count = -1; |
| 24 | + for (auto& kv : memo) { |
| 25 | + max_count = max(max_count, kv.second); |
| 26 | + } |
| 27 | + vector<int> ans; |
| 28 | + for (auto& kv : memo) { |
| 29 | + if (kv.second == max_count) { |
| 30 | + ans.push_back(kv.first); |
| 31 | + } |
| 32 | + } |
| 33 | + return ans; |
| 34 | + } |
| 35 | + |
| 36 | + int getSum(TreeNode* root) { |
| 37 | + if (root == nullptr) |
| 38 | + { |
| 39 | + return 0; |
| 40 | + } |
| 41 | + int sum = root->val + getSum(root->left) + getSum(root->right); |
| 42 | + memo[sum]++; |
| 43 | + return sum; |
| 44 | + } |
| 45 | + |
| 46 | +private: |
| 47 | + unordered_map<int, int> memo; |
| 48 | +}; |
| 49 | +// @lc code=end |
| 50 | + |
0 commit comments