【Leetcode_总结】637. 二叉树的层平均值 - python

Q:

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

示例 1:

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

链接:https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/description/

思路:同 二叉树的层次遍历 将输出取平均值即可

代码:

class Solution:
    def averageOfLevels(self, root):
        """
        :type root: TreeNode
        :rtype: List[float]
        """
        res = []
        que = [root]
        if root == None:
            return res
        while que:
            tempList = []
            for i in range(len(que)):
                node = que.pop(0)
                tempList.append(node.val)
                if node.left:
                    que.append(node.left)
                if node.right:
                    que.append(node.right)
            res.append(sum(tempList)/len(tempList))
        return res

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/86063010