Python BFS


  • 0
    from collections import deque
    
    class Solution(object):
        def levelOrder(self, root):
            res = []
            if root is None:
                return res
            q = deque([root])
            res.append([root.val])
            while q:
                size = len(q)
                level = []
                for i in range(size):
                    node = q.popleft()
                    if node.left != None:
                        q.append(node.left)
                        level.append(node.left.val)
                    if node.right != None:
                        q.append(node.right)
                        level.append(node.right.val)
                if level:
                    res.append(level)
            return res
    

Log in to reply
 

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