508. Most Frequent Subtree Sum

「爱情、让人受尽委屈。」 2024-04-08 09:28 165阅读 0赞

Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.

The subtree sum 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).

Example 1:

5e7e2898d6ffa1d9a55132dae4ff9a95.jpeg

  1. Input: root = [5,2,-3]
  2. Output: [2,-3,4]

Example 2:

f3d4218ae5679b4c9eecb9d675f91c3f.jpeg

  1. Input: root = [5,2,-5]
  2. Output: [2]

题目:给定一个二叉树,找出所有出现次数最多的子树和的值

思路:DFS,用一个hashmap来保存所有字数和出现的次数,代码:

  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. public:
  14. int getSum(TreeNode* node, unordered_map<int, int>& m, int& maxFre){
  15. if(!node) return 0;
  16. int left = getSum(node->left, m, maxFre);
  17. int right = getSum(node->right, m, maxFre);
  18. int sum = node->val + left + right;
  19. m[sum]++;
  20. if(m[sum] > maxFre) maxFre = m[sum];
  21. return sum;
  22. }
  23. vector<int> findFrequentTreeSum(TreeNode* root) {
  24. unordered_map<int, int> m;
  25. int maxFre = 0;
  26. getSum(root, m, maxFre);
  27. vector<int> res;
  28. for(auto mp : m){
  29. if(mp.second == maxFre)
  30. res.push_back(mp.first);
  31. }
  32. return res;
  33. }
  34. };

发表评论

表情:
评论列表 (有 0 条评论,165人围观)

还没有评论,来说两句吧...

相关阅读

    相关 git subtree使用说明

    为什么要使用subtree 在实际的项目开发过程中,公共的代码或者模块是必定会出现的,为了不重复写相同的代码;普遍的做法就是将其抽取成一个公共模块,这个模块由不同的使用者