508. Most Frequent Subtree Sum

难度:Medium

Given the root of a tree, you are asked to find the most frequent subtree sum. 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). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.


题解:这道题融合了两个方面,一个是求树的权,一个是频数的计算,分开解答完毕就可以找到答案。子树的权的求算需要用到迭代,很容易实现


代码如下:

/**
 * 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:
    vector<int>result;
    vector<int> findFrequentTreeSum(TreeNode* root) {
        if(root==NULL)
        {
            return result;
        }
        else if(root->left==NULL&&root->right==NULL)
        {
            result.push_back(root->val);
            return result;
        }
        
       add(result,root);
       sort(result.begin(),result.end());
       vector<int>times;
       times.push_back(1);
       vector<int>value;
       value.push_back(result[0]);
       for(int i=1;i<result.size();i++)
       {
           if(result[i]==value.back())
           {
               times.back()+=1;
           }
           else if(result[i]!=value.back())
           {
               times.push_back(1);
               value.push_back(result[i]);
           }
       }
       int index=findmax(times);
       vector<int>all;
       for(int i=0;i<value.size();i++)
       {
           if(times[index]==times[i])
           all.push_back(value[i]);
       }
       
       return all;
    }
    int findmax(vector<int>vec)
    {
        int index=0;
        int value=vec[0];
        
        for(int i=0;i<vec.size();i++)
        {
            if(vec[i]>=value)
            {
                value=vec[i];
                index=i;
            }
        }
        return index;
    }
    void add(vector<int>&vec,TreeNode* root)
    {
        if(root!=NULL)
        {
            vec.push_back(SumOfRoot(root));
            if(root->left!=NULL)
            add(vec,root->left);
            if(root->right!=NULL)
            add(vec,root->right);
        }
    }
    int SumOfRoot(TreeNode * root)
    {
        if(root==NULL)
        {
            return 0;
        }
        else
        {
            if(root->left==NULL&&root->right==NULL)
            return root->val;
            
            int temp=root->val;
            temp+=SumOfRoot(root->left);
            temp+=SumOfRoot(root->right);
            return temp;
        }
        return 0;
    }
};
可能写得比较麻烦,对树的理解并不透彻,还需要继续精进。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值