Easy to understand python solution, BFS


  • 0
    Y
    class Solution(object):
        def averageOfLevels(self, root):
            if not root: return 0
            import collections
            dic=collections.defaultdict(list)
            queue=collections.deque([(root,1)])
            res=[]
            while queue:
                node,level=queue.popleft()
                dic[level].append(float(node.val))
                if node.left:
                    queue.append([node.left,level+1])
                if node.right:
                    queue.append([node.right,level+1])
            for key,value in dic.items():
                s=sum(value)
                n=len(value)
                res.append(s/float(n))
            return res
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.