题目:
代码:
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def averageOfLevels(self, root):
ans = [root]
print(ans)
target = []
while ans:
n = len(ans)
print(n)
sum = 0
for i in range(n):
r = ans.pop(0)
sum += r.val
if r.left:
ans.append(r.left)
if r.right:
ans.append(r.right)
target.append(sum / (i + 1.0))
return target
if __name__ == '__main__':
inputl_5 = TreeNode(5)
inputl_7 = TreeNode(7)
input2_5 = TreeNode(5)
input2_5.left = inputl_5
input2_5.right = inputl_7
input1_2 = TreeNode(2)
input2_2 = TreeNode(2)
input1_2.left = input2_2
input1_2.right = input2_5
w = Solution()
res = w.averageOfLevels(input1_2)
print('result = ',res)