[Swift]LeetCode979. 在二叉樹中分配硬幣 | Distribute Coins in Binary Tree

原文地址:http://www.javashuo.com/article/p-dbjvcpxe-md.html html

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.node

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.)ui

Return the number of moves required to make every node have exactly one coin. spa

Example 1:3d

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:code

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:htm

Input: [1,0,2]
Output: 2 

Example 4:blog

Input: [1,0,0,null,3]
Output: 4 

Note:get

  1. 1<= N <= 100
  2. 0 <= node.val <= N

給定一個有 N 個結點的二叉樹的根結點 root,樹中的每一個結點上都對應有 node.val 枚硬幣,而且總共有 N 枚硬幣。input

在一次移動中,咱們能夠選擇兩個相鄰的結點,而後將一枚硬幣從其中一個結點移動到另外一個結點。(移動能夠是從父結點到子結點,或者從子結點移動到父結點。)。

返回使每一個結點上只有一枚硬幣所需的移動次數。

 

示例 1:

輸入:[3,0,0]
輸出:2
解釋:從樹的根結點開始,咱們將一枚硬幣移到它的左子結點上,一枚硬幣移到它的右子結點上。

示例 2:

輸入:[0,3,0]
輸出:3
解釋:從根結點的左子結點開始,咱們將兩枚硬幣移到根結點上 [移動兩次]。而後,咱們把一枚硬幣從根結點移到右子結點上。

示例 3:

輸入:[1,0,2]
輸出:2

示例 4:

輸入:[1,0,0,null,3]
輸出:4 

提示:

  1. 1<= N <= 100
  2. 0 <= node.val <= N

28ms 
 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     var ans:Int = 0
16     func distributeCoins(_ root: TreeNode?) -> Int {
17         if root == nil
18         {
19             return 0
20         }
21         travel(root)
22         return ans    
23     }
24     
25     func travel(_ node: TreeNode?) -> [Int]
26     {
27         if node == nil
28         {
29             return [0, 0]
30         }
31         var left:[Int] = travel(node!.left)
32         var right:[Int] = travel(node!.right)
33         if left[0] != left[1]
34         {
35             ans += abs(left[0] - left[1])
36         }
37         if right[0] != right[1]
38         {
39             ans += abs(right[0] - right[1])            
40         }
41         return [node!.val + left[0] + right[0], 1 + left[1] + right[1]]
42     }  
43 }
相關文章
相關標籤/搜索