leetcode编程记录11 #508 Most Frequent Subtree Sum

来源:互联网 发布:趣头条刷阅读量软件 编辑:程序博客网 时间:2024/09/21 06:17

leetcode编程记录11 #508 Most Frequent Subtree Sum

标签(空格分隔): leetcode


这是一道有关树的数据结构的题目,巧妙地利用数据结构可以很快解决这个问题。题目如下:
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.

题目理解与分析:
这道题目的意思是要求我们找出出现次数最多频率的子树和。这里要掌握两个关键,频率最大次数最多这不用多解释;子树的和则是指给定一颗子树,把它所有的节点的值相加所得到的和则是指子树和。所以要找出最大的子树和可以先遍历给定的这棵树,求出每个节点的子树和,将它们保存在哈希表中,并记录一个最大子树和的频率,最后根据该频率从哈希表中找出该子树和。
相应的代码如下:

/** * 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) {        vector<int> result;        sum(root);        for (std::map<int, int>::iterator i = totalSum.begin(); i != totalSum.end(); i++) {            if (count == i->second)            {                result.push_back(i->first);            }        }    return result;    }private:    int count = 0;    map<int, int> totalSum;    int sum(TreeNode* root) {        if (root != NULL) {            int result = sum(root->left) + sum(root->right) + root->val;            if (count < ++totalSum[result])            {                count++;            }            return result;        }        return 0;    }};