首页 > 其他 > 详细

Average of Levels in Binary Tree

时间:2017-09-05 20:44:19      阅读:288      评论:0      收藏:0      [点我收藏+]

    这道题被标记为简单,学过广搜(BFS)应该会很容易做出来

  思路:

    BFS算法搜索每一层的节点,并把他们保存在一个列表a中,再利用循环将这一层的total加起来,并判断当前节点是否有子节点,有就添加到列表的后面,当搜索完一层的节点,就计算每一层的平均值并添加到另外一个新的列表b中,然后再判断是否列表为空,为空就返回列表b,否则就再次循环剩下的。

  代码:

    

 1 class Solution(object):
 2     def averageOfLevels(self, root):
 3         """
 4         :type root: TreeNode
 5         :rtype: List[float]
 6         """
 7         a = [root]
 8         b = []
 9         while len(a) > 0:
10             c = len(a)
11             total = 0.0    
12             for i in range(0, c):
13                 node = a.pop(0)
14                 total += node.val
15                 if node.left:
16                     a.append(node.left)
17                 if no.right:
18                     a.append(node.right)
19             b.append(total / c)
20         return b

  感受:

      开始卡在了从列表读出节点,一直提示错误,因此换了一种方法,浪费了一些空间,刚才试了一下又可以了,很谜

 

Average of Levels in Binary Tree

原文:http://www.cnblogs.com/liuxinzhi/p/7481699.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!