LeetCode 979. Distribute Coins in Binary Tree
原题链接在这里:https://leetcode.com/problems/distribute-coins-in-binary-tree/
题目:
Given the root
of a binary tree with N
nodes, each node
in the tree has node.val
coins, and there are N
coins total.
In one move, we may choose two adjacent nodes and move one coin from one node to another. (The move may be from parent to child, or from child to parent.)
Return the number of moves required to make every node have exactly one coin.
Example 1:
Input: [3,0,0]
Output: 2
Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.
Example 2:
Input: [0,3,0]
Output: 3
Explanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.
Example 3:
Input: [1,0,2]
Output: 2
Example 4:
Input: [1,0,0,null,3]
Output: 4
Note:
1<= N <= 100
0 <= node.val <= N
题解:
Count how many coins current node could give back to its parent.
It could be positive, means having extra coins. Or negative, means needing support from parent. This is the move number, add the absolute value back to result.
The current node, get the count from left child, and count from right right. current node's value plus counts from both left child and right child - 1 is the count that how many coins it could give back to its parent.
Time Complexity: O(n).
Space: O(h).
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 int res = 0; 12 13 public int distributeCoins(TreeNode root) { 14 if(root == null){ 15 return 0; 16 } 17 18 sendCount(root); 19 return res; 20 } 21 22 private int sendCount(TreeNode root){ 23 if(root == null){ 24 return 0; 25 } 26 27 int left = sendCount(root.left); 28 int right = sendCount(root.right); 29 30 int count = root.val + left + right - 1; 31 res += Math.abs(count); 32 return count; 33 } 34 }
【推荐】100%开源!大型工业跨平台软件C++源码提供,建模,组态!
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战
· 优雅求模,一致性哈希算法
· 解疑释惑 - 日志体系之 slf4j + logback 组合(一)
· 平滑加权轮询负载均衡的底层逻辑
· C# 13 与 .NET 9 跨平台开发实战 - 第一章
· DDD领域驱动设计的理解
· 《HelloGitHub》第 113 期
· Git提交错了,别慌!还有后悔药
· 开源一套Microsoft Office COM 组件的 .NET 封装
· ElasticSearch是什么?
· 优雅求模,一致性哈希算法