49ms Python Solution - BFS, beats 87%

  • 0

    Store levels implicitly as indices in an list. And only extend when necessary. Saves a good bit of time.

    import collections
    class Solution(object):
        def levelOrder(self, root):
            :type root: TreeNode
            :rtype: List[List[int]]
            if not root:
                return []
            levels = []
            q = collections.deque([(root,0)])
            while q:
                # N=Node ; L=Level
                N, L = q.popleft()
                if L > len(levels) - 1:
                if N.left:
                    q.append((N.left, L+1))
                if N.right:
                    q.append((N.right, L+1))
            return levels

Log in to reply

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