Python BFS

  • 0
    from collections import deque
    class Solution(object):
        def largestValues(self, root):
            :type root: TreeNode
            :rtype: List[int]
            if not root: return []
            dic = {}
            queue = deque([(root, 0)])
            while queue:
                node, depth = queue.popleft()
                dic[depth] = max(dic.get(depth, float('-inf')), node.val)
                if node.left: queue.append((node.left, depth + 1))
                if node.right: queue.append((node.right, depth + 1))
            return dic.values()

Log in to reply

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