首页 > 其他 > 详细

LeetCode 979. Distribute Coins in Binary Tree

时间:2019-06-26 14:02:28      阅读:116      评论:0      收藏:0      [点我收藏+]

原题链接在这里: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:

 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 }

 

LeetCode 979. Distribute Coins in Binary Tree

原文:https://www.cnblogs.com/Dylan-Java-NYC/p/11089223.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!