Python BFS by ChunChieh Tsai


  • 0
        if not root:
            return []
        # 1. Create a Queue to store
        q = [root]
        result = []
        # 2. While loop to search each layer
        while q:
            new_q = []
            result.append([node.val for node in q])
        # 3. for loop to catch each head
            for node in q:
                
                if node.left:
                    new_q.append(node.left)
                if node.right:
                    new_q.append(node.right)
            q = new_q
        
        
        # 4. return result
        return result

Log in to reply
 

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