LeetCode 979. Distribute Coins in Binary Tree
Posted dylan-java-nyc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于LeetCode 979. Distribute Coins in Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章