Simple Python Code. BFS .O(n)


  • 1

    First get all nodes for each level, then extract val from each nodes

    def levelOrder(self, root):
        res,next=[],[]
        if root:
            temp=[root]
        else:
            return res
        res.append(temp)
        while 1:
            for v in temp:
                if v.left:
                    next.append(v.left)                
                if v.right:
                    next.append(v.right)
            if next==[]:
                break
            res.append(next)
            temp=list(next)
            next=[]
        return [[v.val for v in x] for x in res]

  • 0
    M

    I see .. looks like you are doing this in two steps ;

    (1) populate the nodes in the first parse
    (2) And then append the values of the nodes in the next parse.

    Can you explain a little bit more . as to why you need two lists though ?


  • 0
    K

    this is no need convert to list , because the type of next is list : typetemp=list(next)


Log in to reply
 

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