Python fast without extra space


  • 0
    K

    A static variable d is used to indicate node's level. With it we can just push the visiting nodes one by one to the output list during BFS.

    class Solution(object):
        d=0
        ans=[]
        def __init__(self):
            self.ans = []
        def levelOrder(self, root):
    
            if root == None:
                return []
            
            if self.d>len(self.ans)-1:
                self.ans.append([root.val])
            else:
                self.ans[self.d].append(root.val)
            
            self.d+=1
            self.levelOrder(root.left)
            self.levelOrder(root.right)
            
            self.d-=1
            return self.ans
    

Log in to reply
 

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