Python easy to understand iterative, queue solution

  • 0

    Using python's list as a queue:
    The index acts as a helper to add a new list and to append items to that list

    class Solution(object):
        def levelOrder(self, root):
            :type root: TreeNode
            :rtype: List[List[int]]
            index = 0
            ans, queue = [], [(root, index)]
            while queue:
                node, level = queue.pop(0)
                if node:
                    if len(ans) == level:
                    ans[level] = ans[level] + [node.val]
                    queue.append((node.left, level+1))
                    queue.append((node.right, level+1))
            return ans

Log in to reply

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