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

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

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

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

查看所有标签

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

Impractical Python Projects

Impractical Python Projects

Lee Vaughan / No Starch Press / 2018-11 / USD 29.95

Impractical Python Projects picks up where the complete beginner books leave off, expanding on existing concepts and introducing new tools that you’ll use every day. And to keep things interesting, ea......一起来看看 《Impractical Python Projects》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

html转js在线工具
html转js在线工具

html转js在线工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换