Simple iterative python solution using a queue


  • 0
    N
    def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        queue = []
        queue.append(root)
        queue.append(None)
        returnVal = []
        
        # building a queue that would look like this
        # queue: [7,15,None,20,9,None,3] for the input: [3,9,20,null,null,15,7]
        while queue != []:
            item = queue.pop(0)
            res = []
            if item == None:
                break
            while item:
                if item.left:
                    queue.append(item.left)
                if item.right:
                    queue.append(item.right)
                res.append(item.val)
                item = queue.pop(0)
            queue.append(None)
            returnVal.append(res)
        return returnVal[::-1]

Log in to reply
 

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