LeetCode 637 Average of Levels in Binary Tree (Python)

Posted by 小明MaxMing on March 6, 2021

题目

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

解题思路

从根开始一层一层bfs,遍历的时候求出每层的平均值

代码

class Solution:
    def averageOfLevels(self, root: TreeNode) -> List[float]:
        res = []
        q = [root]
        while q:
            tmp = []
            s = 0
            for n in q:
                s += n.val
                if n.left:
                    tmp.append(n.left)
                if n.right:
                    tmp.append(n.right)
            res.append(s / len(q))
            q = tmp
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅