My AC (Python) solution (BFS) without reversing the list


  • 0
    P

    Simply modified my solution to Binary Tree Level Order Traversal I a bit.
    Same, I put a couple of notes here. For more, please refer to my solution to Binary Tree Level Order Traversal I.

    {

    class Solution:
    def __init__(self):
        self.levels = []
        self.level  = []
        
    def BFS(self):
        if len(self.level) == 0:
            return
    
        currentNodes = self.level
        NodeValues = []
        self.level = []
        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.BFS()
        self.levels.append(NodeValues)
    
    def levelOrderBottom(self, root):
        if root == None:
            return self.levels
    
        if root.right == None and root.left == None:
            self.levels.append([root.val])
            return self.levels
        
        # Initial case
        if root.left != None:
            self.level.append(root.left)
        if root.right != None:
            self.level.append(root.right)
        
        # Start here
        self.BFS()
        self.levels.append([root.val])
        
        return self.levels
    

    }


Log in to reply
 

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