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

查看所有标签

猜你喜欢:

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

捉虫记

捉虫记

施迎 / 清华大学出版社 / 2010-6 / 56.00元

《捉虫记:大容量Web应用性能测试与LoadRunner实战》主要讲解大容量Web性能测试的特点和方法,以及使用业内应用非常广泛的工具——Load Runner 9进行性能测试的具体技术与技巧。《捉虫记:大容量Web应用性能测试与LoadRunner实战》共17章,分为5篇。第1篇介绍软件测试的定义、方法和过程等内容:第2篇介绍Web应用、Web性能测试的分类、基本硬件知识、Web应用服务器选型、......一起来看看 《捉虫记》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

在线进制转换器
在线进制转换器

各进制数互转换器

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具