array based solution, no reverse, no dequeue, using right to left traverse


  • 0
    A
            if root is None:
                return []
    
            thisLvl = [root]
            nxtLvl = []
            ans = [[]]
            toRev = False
            while thisLvl:
                node = thisLvl.pop()
                ans[-1].append(node.val)
                temp = []
                if node.left:
                    temp.append(node.left)
                if node.right:
                    temp.append(node.right)
                if toRev and len(temp)==2:
                    temp.reverse()
                nxtLvl.extend(temp)
                if not thisLvl:
                    toRev = not toRev
                    thisLvl = nxtLvl
                    nxtLvl = []
                    ans.append([])
            ans.pop()
            return ans
    

    I build a list of next level (nxtLvl), while parsing the current level(thisLvl). If the level is odd, append right and then left and if even append left and then right in nxtLvl. Always parse the current level from last to first.


Log in to reply
 

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