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 }
  • 相关阅读:
    Js注释和对象
    卸载Oracle
    数据库设计三大范式
    Oracle用户管理
    Oracle权限管理详解
    Linux 性能监控之CPU&内存&I/O监控Shell脚本2
    Linux 性能监控之CPU&内存&I/O监控Shell脚本1
    Windows Win7建立wifi热点,手机共享WIFI上网
    Mariadb MySQL逻辑条件判断相关语句、函数使用举例介绍
    Mariadb MySQL、Mariadb中GROUP_CONCAT函数使用介绍
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11089223.html
Copyright © 2011-2022 走看看