Here I used `total`

to represent the sum of each level's node values, and `count`

to represent the number of nodes in each level.

```
class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
stack = [(root, 1)] if root else []
total = collections.defaultdict(int)
count = collections.defaultdict(int)
while stack:
node, level = stack.pop()
total[level] += node.val
count[level] += 1
if node.left:
stack.append((node.left, level+1))
if node.right:
stack.append((node.right, level+1))
return [1.0 * total[level] / count[level] for level in sorted(total.keys())]
```