Most Frequent Subtree Sum(C++出现次数最多的子树元素和)

向右看齐 2023-01-16 06:38 193阅读 0赞

解题思路:

(1)后序遍历

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

发表评论

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

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

相关阅读