Leetcode 508. 出现次数最多的子树元素和


给出二叉树的根,找出出现次数最多的子树元素和。一个结点的子树元素和定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。然后求出出现次数最多的子树元素和。如果有多个元素出现的次数相同,返回所有出现次数最多的元素(不限顺序)。

 

示例 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);
	}
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值