Simple and easy understanding Python solution


  • 4
    G
    class Solution(object):
        def levelOrderBottom(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            if not root:
                return []
            
            ans = []
            now = [root]
            while now:
                ans.insert(0, [i.val for i in now])
                now = [j for i in now for j in (i.left, i.right) if j]
            return ans

  • 0
    J

    will anyone 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
    F

    Because the elements of now are all from the same level at a time.


  • 0

    @gene5 This is difficult to understand


  • 0
    L

    @七等星 Depends on how well you know python actually. If you know the insert() function in python I think it is probably easy to understand why the author says it it easy to understand.


Log in to reply
 

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