508. Most Frequent Subtree Sum(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/84256050

题目:

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.
Examples 1
Input:

   5  
  /  \ 
 2   -3 

return [2, -3, 4], since all the values happen only once, return all of them in any order. Examples 2
Input:

   5  
  /  \ 
 2   -5 

return [2], since 2 happens twice, however -5 only occur once.
Note:
You may assume the sum of values in any subtree is in the range of 32-bit signed integer.

解释:
这种问题,很明显要避免重复计算,所以要在dfs的时候做一些记录和更新。
python代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def findFrequentTreeSum(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        _dict={}
        #求当前root下的子树和,子树和出现的次数用字典存
        def dfs(root):
            if not root:
                return 0
            temp=0
            temp+=root.val
            if root.left:
                temp+=dfs(root.left)
            if root.right:
                temp+=dfs(root.right)
            _dict[temp]=_dict.get(temp,0)+1
            return temp
        if not root:
            return []
        dfs(root)
        #感觉这里可以省时间
        result=[]
        max_val=1
        for key in _dict:
            if _dict[key]==max_val:
                result.append(key)
            elif _dict[key]>max_val:
                max_val=_dict[key]
                result=[key]
        return result

c++代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include <map>
using namespace std;
class Solution {
public:
    map<int,int>countofSum;
    vector<int> findFrequentTreeSum(TreeNode* root) {
        vector<int> result;
        if(!root)
            return result;
        getSum(root);
        int max_val=1;
        for(auto item:countofSum)
        {
            if (item.second==max_val)
                result.push_back(item.first);
            else if(item.second>max_val)
            {
                max_val=item.second;
                result={item.first};
            }  
        }
        return result;
    }
    int getSum(TreeNode* root)
    {
        if(!root)
            return NULL;
        int tmpSum=root->val;
        if(root->left)
            tmpSum+=getSum(root->left);
        if(root->right)
            tmpSum+=getSum(root->right);
        countofSum[tmpSum]+=1;
        return tmpSum;
    }
};

总结:
需要注意的就是在遍历的过程中更新map,这样可以有效避免重复计算。

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/84256050
今日推荐