给出二叉树的根,找出出现次数最多的子树元素和。一个结点的子树元素和定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。然后求出出现次数最多的子树元素和。如果有多个元素出现的次数相同,返回所有出现次数最多的元素(不限顺序)。
示例 1
输入:
5 / \ 2 -3
返回 [2, -3, 4],所有的值均只出现一次,以任意顺序返回所有值。
示例 2
输入:
5 / \ 2 -5
返回 [2],只有 2 出现两次,-5 只出现 1 次。
基本思路:先把每个节点的子树元素和算出来,再遍历整个树。
class Solution {
public:
vector<int> findFrequentTreeSum(TreeNode* root) {
vector<int> Res;
map<int, int> Hash;
if (root == NULL) return Res;
_findFrequentTreeSum(root);
Find_Fuck(Hash, root);
int Max = 0;
map<int, int>::iterator Inter = Hash.begin();
while (Inter!= Hash.end()) {
Max = max(Inter++->second, Max);
}
Inter = Hash.begin();
while (Inter != Hash.end()) {
if (Inter->second == Max)
Res.push_back(Inter->first);
Inter++;
}
return Res;
}
// 计算整个树的元素和
int _findFrequentTreeSum(TreeNode* root) {
if (root->left == NULL && root->right == NULL)
return root->val;
if (root->left != NULL) {
root->val += _findFrequentTreeSum(root->left);
}
if (root->right != NULL) {
root->val += _findFrequentTreeSum(root->right);
}
return root->val;
}
// 使用一个Map来储存每个子树元素和出现的次数
void Find_Fuck(map<int, int>& Hash, TreeNode* root) {
if (root == NULL) return;
map<int, int>::iterator Inter = Hash.find(root->val);
if (Inter == Hash.end())
Hash.insert(pair<int, int>(root->val, 1));
else{
Inter->second++;
}
Find_Fuck(Hash, root->left);
Find_Fuck(Hash, root->right);
}
};