Simple Python Solution


  • 0
    S
    class Solution:
    # @param {TreeNode} root
    # @return {integer[][]}
    def levelOrder(self, root):
        traversal = []
        if root:
            self.recurse([root], traversal)
        return traversal
    
    def recurse(self, q, traversal):
        temp = []
        new_q = []
        while q:
            current = q.pop(0)
            if current.left:
                new_q.append(current.left)
            if current.right:
                new_q.append(current.right)
            temp.append(current.val)
        traversal.append(temp)
        if not new_q:
            return
        self.recurse(new_q, traversal)

  • 1

    q.pop(0) takes linear time every time, as it has to shift all elements. Instead of

    while q:
        current = q.pop(0)
    

    better do a normal loop:

    for current in q:

Log in to reply
 

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