Using a queue in Python


  • 0
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    from collections import deque
    
    class Solution(object):
        def levelOrderBottom(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            results = []
            
            if not root : 
                return results
                
            queue = deque([root])
            
            while queue:
                level = []
                for i in range(len(queue)):
                    front = queue.popleft()
                    level.append(front.val)
                    if front.left:
                        queue.append(front.left)
                    if front.right:
                        queue.append(front.right)
                results.append(level)
            
            return results[::-1]

Log in to reply
 

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