加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

【python-leetcode637-树的宽度遍历】二叉树的层平均值

发布时间:2020-12-20 09:54:28 所属栏目:Python 来源:网络整理
导读:给定一个非空二叉树,返回一个由每层节点平均值组成的数组. 示例 1: 输入: 3 / 9 20 ? ? / ? 15 7 输出: [3,14.5,11] 解释: 第0层的平均值是 3,第1层是 14.5,第2层是 11. 因此返回 [3,11]. 注意: 节点值的范围在32位有符号整数范围内。 ? # Definition f

给定一个非空二叉树,返回一个由每层节点平均值组成的数组.

示例 1:

输入:
3
/
9 20
? ? /
? 15 7
输出: [3,14.5,11]
解释:
第0层的平均值是 3,第1层是 14.5,第2层是 11. 因此返回 [3,11].
注意:

节点值的范围在32位有符号整数范围内。

?

# Definition for a binary tree node.
# class TreeNode:     def __init__(self,x):         self.val = x         self.left = None         self.right = None

class Solution:
    def averageOfLevels(self,root: TreeNode) -> List[float]:
        if  not root:
            return []
        queue=[root]
        res=[]
        while queue:
            s=0
            l=len(queue)
            for i in range(l):
                t=queue.pop(0)
                s+=t.val
                if t.left:
                    queue.append(t.left)
                 t.right:
                    queue.append(t.right)
            res.append(float(s)/float(l))
        return res

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读