[Leetcode] 508. Most Frequent Subtree Sum 解题报告

本文介绍了一种算法,用于找到给定树中最频繁出现的子树和,并返回这些值。通过递归方法和哈希表的应用,文章详细解释了如何高效地解决这一问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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.

思路

我们在C++实现中,让哈希表和最大出现次数用传地址的方式,这样可以在递归的过程中得到更新;同时返回以root为根的子树的sum,便于更快的计算当前root对应树的sum。最后挑选出出现次数为max_frequent的和即可。整个算法的时间复杂度是O(n + m),其中n是树中的节点个数,m是和的个数。这种类型的题目的时间复杂度好像叫做“输入敏感的”,也就是说不同的输入会导致m的值处于不同的量级。不过对于这道题目而言,我们一般可以认为m的量级大于n。

代码

/**
 * 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> findFrequentTreeSum(TreeNode* root) {
        if (root == NULL) {
            return {};
        }
        unordered_map<int, int> hash;
        int max_frequent = 0;
        findFrequentTreeSum(root, hash, max_frequent);
        vector<int> ret;
        for (auto it = hash.begin(); it != hash.end(); ++it) {
            if (it->second == max_frequent) {
                ret.push_back(it->first);
            }
        }
        return ret;
    }
private:
    int findFrequentTreeSum(TreeNode *root, unordered_map<int, int> &hash, int &max_frequent) {
        int sum = root->val;        // precondition: root cannot be NULL
        if (root->left) {
            sum += findFrequentTreeSum(root->left, hash, max_frequent);
        } 
        if (root->right) {
            sum += findFrequentTreeSum(root->right, hash, max_frequent);
        }
        ++hash[sum];
        max_frequent = max(max_frequent, hash[sum]);
        return sum;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值