LeetCode Most Frequent Subtree Sum

LeetCode Most Frequent Subtree Sum 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.
给定一棵二叉树,问频率最大的子树之和是哪个数。子树之和是指根节点及其子节点的和。 简单题,使用后序遍历把所有子树之和统计一遍,用Hash记录和与频率的关系,然后找出最大频率的和。 代码如下: [cpp] class Solution { private: int postOrder(TreeNode* root, unordered_map<int, int>& hash) { int sum = 0; if (root->left)sum += postOrder(root->left, hash); if (root->right)sum += postOrder(root->right, hash); sum += root->val; ++hash[sum]; return sum; } public: vector<int> findFrequentTreeSum(TreeNode* root) { if (!root)return vector<int>(); unordered_map<int, int> hash; postOrder(root, hash); int maxCnt = 0; for (auto it = hash.begin(); it != hash.end(); ++it)maxCnt = max(maxCnt, (*it).second); vector<int> ans; for (auto it = hash.begin(); it != hash.end(); ++it) { if ((*it).second == maxCnt)ans.push_back((*it).first); } return ans; } }; [/cpp] 本代码提交AC,用时19MS。]]>

Leave a Reply

Your email address will not be published. Required fields are marked *