Python BFS neat code


  • 0

    Please let me know if there are something can be improved:)

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def levelOrderBottom(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            if root == None:
                return []
            queue, res = [root], []
            while not len(queue) == 0:
                values, temp = [], []
                for node in queue:
                    if not node.left == None:
                        temp += [node.left]
                    if not node.right == None:
                        temp += [node.right]
                    values += [node.val]
                res = [values] + res
                queue = temp
            return res
    

Log in to reply
 

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