Simple python solution using deque


  • 0
    Y
    class Solution:
    # @param {TreeNode} root
    # @return {integer[][]}
    def levelOrder(self, root):
        if not root:
            return []
    
        q = deque()
        q.append(root)
        q.append(None)
        res = []
        curr = []
        while True:
            node = q[0]
            q.popleft()
            if not node:
                res.append(curr)
                if len(q) == 0:
                    break
                else:
                    q.append(None)
                    curr = []
            else:
                curr.append(node.val)
                if node.left: q.append(node.left)
                if node.right: q.append(node.right)
        return res

Log in to reply
 

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