637. 二叉树的层平均值




BFS模板的应用。

总结的DFS、BFS模板参考:https://www.cnblogs.com/panweiwei/p/13065661.html

注:"/"符号两边只要有一个float类型,结果自动取float类型!!!

class Solution(object):
    def averageOfLevels(self, root):
        """
        :type root: TreeNode
        :rtype: List[float]
        """
        if not root:
            return []
        ans = []
        queue = [root]
        # 外层while遍历的是树的层数
        while queue:
            temp = []
            l = len(queue)
            # 内层for遍历的是每层中的节点数
            for i in range(l):
                node = queue.pop(0)
                temp.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            print(temp, l)
            # "/"符号两边只要有一个float类型,结果自动取float类型!!!
            ans.append(sum(temp)/float(l))
        return ans
posted @ 2020-09-13 15:51  人间烟火地三鲜  阅读(119)  评论(0编辑  收藏  举报