508. Most Frequent Subtree Sum(python+cpp)

本文探讨了在给定树的根节点时,如何找出最频繁出现的子树和。通过深度优先搜索(DFS)算法,并使用哈希映射记录每个子树和的频率,有效地解决了问题。提供了Python和C++的实现代码。

题目:

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,这样可以有效避免重复计算。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值