原题链接在这里: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. 1<= N <= 100
  2. 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:

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int res = 0; public int distributeCoins(TreeNode root) {
if(root == null){
return 0;
} sendCount(root);
return res;
} private int sendCount(TreeNode root){
if(root == null){
return 0;
} int left = sendCount(root.left);
int right = sendCount(root.right); int count = root.val + left + right - 1;
res += Math.abs(count);
return count;
}
}

最新文章

  1. iOS 开发之崩溃日志分析
  2. 【编辑器】【Sublime Text】使用笔记
  3. Linux 安装Weblogic12 - copy
  4. [No000052]大蒜怎么吃最美容?吃大蒜的功效及禁忌
  5. A Tour of Go Switch
  6. Ubuntu 12.04 wine QQ
  7. Linux的文件/目录访问权限
  8. 用Windows Live Writer 2012发博客
  9. python mysql多条插入
  10. 经典排序算法 - 基数排序Radix sort
  11. Angularjs 基于karma和jasmine的单元测试
  12. Leetcode-33-Search in Rotated Sorted Array (Hard)
  13. jQuery选择器(ID选择器)第一节
  14. Swift百万线程攻破单例(Singleton)模式
  15. 第一本Docker书读书笔记
  16. 《你不知道的JavaScript(上卷)》读书笔记
  17. 机器学习算法中如何选取超参数:学习速率、正则项系数、minibatch size
  18. 软工实践——结对作业2【wordCount进阶需求】
  19. eclipse git 拉取内容
  20. Tomorrow Is A New Day

热门文章

  1. 基于DigitalOcean+LAMP+WordPress搭建个人网站
  2. Delphi编码与签名【URL编码与解码,Base64编码与解码,MD5加密,HMAC-SHA1、HMAC-SHA224、HMAC-SHA256、HMAC-SHA384和HMAC-SHA512签名】
  3. Python之路【第三十一篇】:django ajax
  4. AVR单片机教程——数码管
  5. Docker之Alpine制作镜像且上传至阿里云
  6. 对于Node中Express框架的中间件概念的感知
  7. SP375 QTREE - Query on a tree (树剖)
  8. 十二.作业难点(有IT大牛路过的可以帮我解答我的疑问?万分感谢)--转行的苦逼人
  9. 必须掌握的Linux用户组
  10. 虚拟Dom详解 - (二)