内容简介:返回每一层的平均值。和前一篇相似。先保存每一层的值,再逐层计算平均值即可。
D56 637. Average of Levels in Binary Tree
题目链接
637. Average of Levels in Binary Tree
题目分析
返回每一层的平均值。
思路
和前一篇相似。先保存每一层的值,再逐层计算平均值即可。
最终代码
<?php
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($value) { $this->val = $value; }
* }
*/
class Solution {
/**
* @param TreeNode $root
* @return Float[]
*/
public $level = 0;
public $values = [];
function averageOfLevels($root) {
$this->levelValues($root);
$avg = [];
foreach($this->values as $values){
$avg[] = array_sum($values)/count($values);
}
return $avg;
}
function levelValues($root){
if(is_null($root)){
return $this->values;
}
if(!isset($this->values[$this->level])){
$this->values[$this->level] = [];
}
$this->values[$this->level][] = $root->val;
if($root->left){
$this->level++;
$this->averageOfLevels($root->left);
$this->level--;
}
if($root->right){
$this->level++;
$this->averageOfLevels($root->right);
$this->level--;
}
return $this->values;
}
}
若觉得本文章对你有用,欢迎用 爱发电 资助。
以上所述就是小编给大家介绍的《Leetcode PHP题解--D56 637. Average of Levels in Binary Tree》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
设计原本
Frederick P. Brooks, Jr. / InfoQ中文站、王海鹏、高博 / 机械工业出版社 / 2011-1-1 / 55.00元
无论是软件开发、工程还是建筑,有效的设计都是工作的核心。《设计原本:计算机科学巨匠Frederick P. Brooks的思考》将对设计过程进行深入分析,揭示进行有效和优雅设计的方法。 本书包含了多个行业设计者的特别领悟。Frederick P. Brooks, Jr.精确发现了所有设计项目中内在的不变因素,揭示 了进行优秀设计的过程和模式。通过与几十位优秀设计者的对话,以及他自己在几个设计......一起来看看 《设计原本》 这本书的介绍吧!
XML、JSON 在线转换
在线XML、JSON转换工具
正则表达式在线测试
正则表达式在线测试