博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode] 1120. Maximum Average Subtree
阅读量:4709 次
发布时间:2019-06-10

本文共 2388 字,大约阅读时间需要 7 分钟。

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

(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.00000Explanation: 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.

 

===================================================================

C#

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 public class Solution { 5     List
avgs = new List
(); 6 public double MaximumAverageSubtree(TreeNode root) 7 { 8 int counter = 0; 9 double summer = 0;10 var result = TreeTraverse(root,ref counter,ref summer);11 12 return avgs.Max();13 }14 15 public double? TreeTraverse(TreeNode subTreeRoot,ref int counter,ref double summer)16 {17 if(subTreeRoot == null)18 {19 return null;20 }21 int leftCounter = 0;22 int rightCounter = 0;23 double leftSummer = 0;24 double rightSummer = 0;25 26 double? leftSum = TreeTraverse(subTreeRoot.left,ref leftCounter,ref leftSummer);27 28 if (false == leftSum.HasValue)29 {30 leftSum = 0;31 }32 else33 counter++;34 35 double? rightSum = TreeTraverse(subTreeRoot.right,ref rightCounter,ref rightSummer);36 37 if (false == rightSum.HasValue)38 {39 rightSum = 0;40 }41 else42 counter++;43 44 counter = (leftCounter + rightCounter + 1);45 summer = (leftSummer + rightSummer + subTreeRoot.val);46 avgs.Add(summer / counter);47 48 return subTreeRoot.val;49 }50 }

 

转载于:https://www.cnblogs.com/seako/p/11186547.html

你可能感兴趣的文章
表达式括号匹配
查看>>
“耐撕”团队2016.04.19站立会议
查看>>
JQuery:empty选择器
查看>>
[NOI2016]优秀的拆分 后缀数组
查看>>
菜鸟的逆袭 - 自我介绍
查看>>
<Bootstrap> 学习笔记二. 栅格系统的使用
查看>>
Codeforces Round #404 (Div. 2) E. Anton and Permutation 分块
查看>>
xml
查看>>
this 和 new 构造函数
查看>>
阅读和提问作业3
查看>>
【杂谈接口】接口对象的生命周期-对象所占用的内存块清理
查看>>
Full GC为什么那么慢?为什么老年代垃圾回收效率比新生代低很多?为什么Minor gc速度比Major GC慢?...
查看>>
关于动态生成data组件
查看>>
Docker镜像优化
查看>>
win7下mysql8.0.12解压缩版安装
查看>>
Linux Tomcat
查看>>
刷题的第一天。【并不是
查看>>
java类型生命周期
查看>>
asp.net Mvc Npoi 导出导入 excel
查看>>
vue-cli脚手架搭建项目整理笔记
查看>>