My AC (Python) solution (BFS)


  • 0
    P

    The following solution is easy to understand. And I also put a couple of notes by comments.

    {

    class Solution:
    
    def __init__(self):
        self.levels = []  # used to keep track of node values level by level
        self.level   = []  # used to keep track of nodes level by level
        
    def BFS(self):
        if len(self.level) == 0:
            return
    
        currentNodes = self.level
        NodeValues = []          # buffer to store values of nodes of the current level
        self.level = []                # reset
        for eachNode in currentNodes:
            if eachNode.left  != None:
                self.level.append(eachNode.left)
            if eachNode.right != None:
                self.level.append(eachNode.right)
            NodeValues.append(eachNode.val)
        self.levels.append(NodeValues)
        
        #currentNodes.clear()  # This may save space
        self.BFS()
    
    def levelOrder(self, root):
        if root == None:
            return self.levels
    
        if root.right == None and root.left == None:
            self.levels.append([root.val])
            return self.levels
    
        self.levels.append([root.val])
        
        if root.left != None:
            self.level.append(root.left)
        if root.right != None:
            self.level.append(root.right)
    
        self.BFS()        
        
        return self.levels
    

    }


Log in to reply
 

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