python easy to understand - iterative:BFS using queue


  • 0
    M
        def levelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            if not root:
                return []
            q = collections.deque()
            q.append(root)
            out = []
            
            while q:
                levelNum = len(q)
                tmp = []
                
                for i in range(levelNum):
                    node = q.popleft()
                    tmp.append(node.val)
                    
                    if node.left is not None:
                        q.append(node.left)
                        
                    if node.right is not None:
                        q.append(node.right)
                        
                out.append(tmp)
                    
            return out
    

Log in to reply
 

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