Short python solution


  • 7
    C
    # 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]]
            """
            answ, L = [], [root]
            while L and root:
                answ.insert(0,[n.val for n in L])
                L = [ C for N in L for C in (N.left,N.right) if C ]
            return answ

  • 2
    Q
    class Solution(object):
        def levelOrderBottom(self, root):
            res, nodes = [], [root] if root else []
            while nodes:
                res.append(list(node.val for node in nodes))
                nodes = [x for node in nodes for x in (node.left, node.right) if x]
            res.reverse()
            return res

  • 0
    J

    Hello, will you be able to explain what happens during the while loops? how do you change the level of the tree (if [3, 9, 20, null, null, 15,7]) from first level [3] to second level [9,20]? it seen like after the nest for loop the level auto change to the next level?


  • 0
    X
    This post is deleted!

  • 0
    L

    @cygnx Not sure why this has up votes considering insert at 0 is O(n) operation. It would've made more sense to do the same the first level order problem and just reverse the answer...that would've been faster


Log in to reply
 

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