using list to simulate queue, bfs solution in python


  • 0
    F
        def averageOfLevels(self, root):
            queue, result = [root], []
            while queue:
                size = len(queue)
                total = 0.0
                for _ in range(size):
                    node = queue.pop()
                    total += node.val
                    if node.left:
                        queue.insert(0, node.left)
                    if node.right:
                        queue.insert(0, node.right)
                result.append(total / size)
            return result

Log in to reply
 

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