LeetCode 979 Distribute Coins in Binary Tree

本文介绍了一种解决二叉树中节点金币分配问题的算法。通过递归遍历二叉树,统计每个节点的子树节点数与金币总数,计算节点与金币数量的不平衡量,最终求得整个二叉树最小金币移动次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 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:
	int res = 0;
	pair<int, int> dfs(TreeNode* root) {

		pair<int, int> p;
		p.first = 1;
		p.second = root->val;   
		if (root->left != NULL) {
			pair<int, int> x = dfs(root->left);
			p.first += x.first;
			p.second += x.second;
		}
		if (root->right != NULL) {
			pair<int, int> x = dfs(root->right); 
			p.first += x.first;
			p.second += x.second;
		}
		res += abs(p.first - p.second);
        return p;
	}
	int distributeCoins(TreeNode* root) {
		dfs(root);

		return res;
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值