508. Most Frequent Subtree Sum

来源:互联网 发布:mysql emoji 截断 编辑:程序博客网 时间:2024/05/22 06:16

难度: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;    }};
可能写得比较麻烦,对树的理解并不透彻,还需要继续精进。