出现次数最多的子树元素和

给出二叉树的根,找出出现次数最多的子树元素和。一个结点的子树元素和定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。然后求出出现次数最多的子树元素和。如果有多个元素出现的次数相同,返回所有出现次数最多的元素(不限顺序)。

 

示例 1
输入:

  5
 /  \
2   -3
返回 [2, -3, 4],所有的值均只出现一次,以任意顺序返回所有值。

示例 2
输入:

  5
 /  \
2   -5
返回 [2],只有 2 出现两次,-5 只出现 1 次。

 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/most-frequent-subtree-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    
    unordered_map<int, int> iMap;
    vector<int> ret;
    vector<int> findFrequentTreeSum(TreeNode* root) 
    {
        if(root == NULL)
            return ret;
        bianli(root);
        vector<pair<int, int>> vtMap;
        for (auto it = iMap.begin(); it != iMap.end(); it++)
            vtMap.push_back(make_pair(it->first, it->second));

        sort(vtMap.begin(), vtMap.end(), 
            [](const pair<int, int> &x, const pair<int, int> &y) -> int {
            return x.second > y.second;
        });
        int times = vtMap.begin()->second;
        for (auto it = vtMap.begin(); it != vtMap.end(); it++)
        {
            if(it->second == times)
            {
                ret.push_back(it->first);
            }
        }
        return ret;
    }
    
    void bianli(TreeNode* root)
    {
        if(root != NULL)
        {
            int sum = 0;
            qiuhe(root, sum);
            //ret.push_back(sum);
            iMap[sum]++;
            bianli(root->left);
            bianli(root->right);
        }
    }
    
    void qiuhe(TreeNode* root, int& sum)
    {
        if(root != NULL)
        {
            sum += root->val;
            qiuhe(root->left, sum);
            qiuhe(root->right, sum);
        }
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值