leetcode508

经典的树的DFS搜索,采用map操作,得到result和出现的次数的对照表格,然后利用机械的方法,得到最大次数对应的result值。

在这个问题中,竟然因为
iterator的使用浪费大量时间,不值得推崇。

/**
 * 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:

    map<int,int> countMap;

    int sum(TreeNode * root)
    {
        if(root==NULL) 
            return 0;
        else
        {
            int result = sum(root->left)+sum(root->right)+root->val;   

            if(countMap.count(result)==0)
                countMap[result]=1;
            else
                countMap[result]++;

            return result;
        }
    }

    vector<int> findFrequentTreeSum(TreeNode* root) {

        vector<int> frequentNum;
        if (root==NULL)
            return frequentNum;
        else
        {
            sum(root);

            map<int,int>::iterator it=countMap.begin();

            int maxFre=(it)->second;
            for(it;it!=countMap.end();it++)
            {
                if(it->second>maxFre)
                    maxFre=it->second;
            }

            for(it=countMap.begin();it!=countMap.end();it++)
            {
                if(maxFre==it->second)
                    frequentNum.push_back(it->first);
            }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值