[Swift]LeetCode1120. 子樹的最大平均值 | Maximum Average Subtree

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-kyrmynjf-kx.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given the root of a binary tree, find the maximum average value of any subtree of that tree.node

(A subtree of a tree is any node of that tree plus all its descendants. The average value of a tree is the sum of its values, divided by the number of nodes.) git

Example 1:github

Input: [5,6,1]
Output: 6.00000 Explanation: For the node with value = 5 we have and average of (5 + 6 + 1) / 3 = 4. For the node with value = 6 we have and average of 6 / 1 = 6. For the node with value = 1 we have and average of 1 / 1 = 1. So the answer is 6 which is the maximum. 

 

Note:微信

  1. The number of nodes in the tree is between 1 and 5000.
  2. Each node will have a value between 0 and 100000.
  3. Answers will be accepted as correct if they are within 10^-5 of the correct answer.

給你一棵二叉樹的根節點 root,找出這棵樹的 每一棵 子樹的 平均值 中的 最大 值。ide

子樹是樹中的任意節點和它的全部後代構成的集合。spa

樹的平均值是樹中節點值的總和除以節點數。 code

示例:htm

輸入:[5,6,1]
輸出:6.00000
解釋: 
以 value = 5 的節點做爲子樹的根節點,獲得的平均值爲 (5 + 6 + 1) / 3 = 4。
以 value = 6 的節點做爲子樹的根節點,獲得的平均值爲 6 / 1 = 6。
以 value = 1 的節點做爲子樹的根節點,獲得的平均值爲 1 / 1 = 1。
因此答案取最大值 6。 

提示:blog

  1. 樹中的節點數介於 1 到 5000之間。
  2. 每一個節點的值介於 0 到 100000 之間。
  3. 若是結果與標準答案的偏差不超過 10^-5,那麼該結果將被視爲正確答案。

88ms

 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 ret:Double = 0
16     func maximumAverageSubtree(_ root: TreeNode?) -> Double {
17         if root == nil {return ret}
18         dfs(root)
19         return ret        
20     }
21     
22     func dfs(_ root: TreeNode?) -> (Int,Int)
23     {
24         var cal:Int = 1
25         var sum:Int = root!.val
26         if root!.left != nil
27         {
28             var test:(Int,Int) = dfs(root!.left)
29             cal += test.0
30             sum += test.1
31         }
32         if root!.right != nil
33         {
34             var test:(Int,Int) = dfs(root!.right)
35             cal += test.0
36             sum += test.1
37         }
38         let temp:Double = Double(sum) / Double(cal)
39         if ret < temp
40         {
41             ret = temp
42         }
43         return (cal, sum)
44     }
45 }
相關文章
相關標籤/搜索