Python BFS Solution


  • 0
    6
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    import queue
    class Solution:
        def averageOfLevels(self, root):
            """
            :type root: TreeNode
            :rtype: List[float]
            """
            ans = []
            q = queue.Queue()
            q.put(root)
            while not q.empty():
                n = q.qsize()
                sum0 = 0
                for x in range(n):
                    node = q.get()
                    sum0 += node.val
                    if node.left: q.put(node.left)
                    if node.right: q.put(node.right)
                ans.append(sum0/n)
            return ans

Log in to reply
 

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