zoukankan      html  css  js  c++  java
  • 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. 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 }
  • 相关阅读:
    Maven3核心技术(笔记三)
    解决Ubuntu下Sublime Text 3无法输入中文
    python3项目之数据可视化
    Python模块Pygame安装
    PHP命名空间(Namespace)
    git的安装使用和代码自动部署
    input:text 的value 和 attribute('value') 不是一回事
    touch事件学习
    获得 选中文字
    linux使用crontab实现PHP执行定时任务及codeiginter参数传递相关
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11089223.html
Copyright © 2011-2022 走看看