内容简介:返回每一层的平均值。和前一篇相似。先保存每一层的值,再逐层计算平均值即可。
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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
JavaScript修炼之道
波顿纽威 / 巩朋、张铁 / 人民邮电 / 2011-11 / 29.00元
《JavaScript修炼之道》是JavaScript的实战秘籍。作者将自己多年的编程经验融入其中,不仅可以作为学习之用,更是日常JavaScript开发中不可多得的参考手册,使读者少走很多弯路。《JavaScript修炼之道》的内容涵盖了当今流行的JavaScript库的运行机制,也提供了许多应用案例。《JavaScript修炼之道》针对各任务采取对页式编排,在对各任务的讲解中,左页解释了任务的......一起来看看 《JavaScript修炼之道》 这本书的介绍吧!