Python BFS Solution with Queue


  • 0
    Y

    The idea is to traversal the tree and save the node into hashtable, and export the maximum of each level.

    class Solution(object):
        def largestValues(self, root):
            if not root:return []
            queue=collections.deque([(root,1)])
            dic=collections.defaultdict(list)
            while queue:
                root,level=queue.popleft()
                if not root:
                    continue
                dic[level].append(root.val)
                if root.left:
                    queue.append((root.left,level+1))
                if root.right:
                    queue.append((root.right,level+1))
            res=[]
            for key in sorted(dic):
                res.append(max(dic[key]))
            return res
    #78 / 78 test cases passed.
    #Status: Accepted
    #Runtime: 76 ms
    

Log in to reply
 

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