Leetcode PHP题解--D56 637. Average of Levels in Binary Tree

栏目: PHP · 发布时间: 5年前

内容简介:返回每一层的平均值。和前一篇相似。先保存每一层的值,再逐层计算平均值即可。

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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

SQL进阶教程

SQL进阶教程

[ 日] MICK / 吴炎昌 / 人民邮电出版社 / 2017-11 / 79.00元

本书是《SQL基础教程》作者MICK为志在向中级进阶的数据库工程师编写的一本SQL技能提升指南。全书可分为两部分,第一部分介绍了SQL语言不同寻常的使用技巧,带领读者从SQL常见技术,比如CASE表达式、自连接、HAVING子句、外连接、关联子查询、EXISTS……去探索新发现。这部分不仅穿插讲解了这些技巧背后的逻辑和相关知识,而且辅以丰富的示例程序,旨在帮助读者提升编程水平;第二部分着重介绍关系......一起来看看 《SQL进阶教程》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具