在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given the (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.) Example 1: 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:
给你一棵二叉树的根节点 子树是树中的任意节点和它的所有后代构成的集合。 树的平均值是树中节点值的总和除以节点数。 示例: 输入:[5,6,1] 输出:6.00000 解释: 以 value = 5 的节点作为子树的根节点,得到的平均值为 (5 + 6 + 1) / 3 = 4。 以 value = 6 的节点作为子树的根节点,得到的平均值为 6 / 1 = 6。 以 value = 1 的节点作为子树的根节点,得到的平均值为 1 / 1 = 1。 所以答案取最大值 6。 提示:
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 }
|
请发表评论