Leetcode637. BFS计算二叉树每层节点的平均值

突然发现自己的数据结构内容全忘了!!!!

二叉树的知识我天,还要补!!!

题目
Input: 

/ \ 
9 20 
/ \ 
15 7

Output: [3, 14.5, 11]

Explanation: 
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].

解题分析
从题目的示例我们可以大概知道题目要求我们遍历二叉树的每层节点并计算其平均值。二叉树的搜索遍历无外乎这几种方法:先序遍历、中序遍历、后序遍历、BFS、DFS。结合题目,很显然BFS是比较适合题目的一种方法。那么问题来了,怎样使得二叉树每层的节点是从左至右遍历的,进而计算其节点个数和节点总和。

我们不妨用队列来思考这个问题。我们先往队列中push根节点,然后当队列不为空的时候,遍历整个队列。每遍历队列中的一个节点,就取出它的值并将其pop。此时顺带检查它的左右子节点是否为空,如果不为空,就将其子节点push进入队列中。这样,刚好遍历完一层节点,下一层的节点就全部存到队列中了。一层层循环下去直到最后一层,问题便顺利得到了解决。

源代码

    
from collections import deque
class Solution(object):
    def averageOfLevels(self, root):   
        ans = []
        queue = deque([root])
        while queue:
            s = 0
            n = len(queue)
            for _ in range(n):
                top = queue.popleft()
                s += top.val
                if top.left:
                    queue.append(top.left)
                if top.right:
                    queue.append(top.right)
            ans.append(float(s) / n)
        return ans

猜你喜欢

转载自blog.csdn.net/qq_35290785/article/details/89027728