Python Solution. Beats 96 % Submission.


  • 0
    D

    This is a BFS solution that does not use a queue data structure. Instead I use an index to keep track of where we are at in the list.

    def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        
        solutions = []
        
        if not root:
            return solutions
    
        q = [root]
        i = 0
        
        while i < len(q):
            level = []
            for j in range(0, len(q) - i):
                n = q[i]
                level.append(n.val)
                if n.left:
                    q.append(n.left)
                if n.right:
                    q.append(n.right)
                i += 1
            # insert at the front of the list, this is better than reversing at the end
            solutions.insert(0,level)
        
        return solutions

  • 0
    V

    Surprised this solution beats 96% it seems inefficient to me. However I will say I think it is pretty concise. Like the simplicity.


Log in to reply
 

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