Average of Levels in Binary Tree
阿新 • • 發佈:2017-09-05
append urn pan 返回 把他 right app 代碼 錯誤
這道題被標記為簡單,學過廣搜(BFS)應該會很容易做出來
思路:
BFS算法搜索每一層的節點,並把他們保存在一個列表a中,再利用循環將這一層的total加起來,並判斷當前節點是否有子節點,有就添加到列表的後面,當搜索完一層的節點,就計算每一層的平均值並添加到另外一個新的列表b中,然後再判斷是否列表為空,為空就返回列表b,否則就再次循環剩下的。
代碼:
1 class Solution(object): 2 def averageOfLevels(self, root): 3 """ 4 :type root: TreeNode5 :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