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

来源:互联网 发布:网络安全工程师招聘 编辑:程序博客网 时间:2024/06/10 20:31

题目

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;    }};

原创粉丝点击