Given a non-null binary tree, each node returns an array of the average value thereof.
Example 1:
Input:
3
/ \
920
/ \
157
Output: [3, 14.5, 11]
Explanation:
average value of 0 is 3 layer, the first layer 14.5, the second layer 11 is thus returned [3, 14.5, 11]
Note:
Node value in a range of 32-bit signed integer within the range.
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def averageOfLevels(self, root: TreeNode) -> List[float]: if not root: return [] queue=[root] res=[] while queue: s=0 l=len(queue) for i in range(l): t=queue.pop(0) s+=t.val if t.left: queue.append(t.left) if t.right: queue.append(t.right) res.append(float(s)/float(l)) return res