7-line fast python solution (48ms)


  • 0
    C

    Based on my shared solution for Binary Tree Level Order Traversal. With the following trick, we only need one more line to change reverse in each loop

    (-1)**reverse = -1 when reverse ==True

    (-1)**reverse = 1 when reverse ==False



    Solution 1, 7 lines

    def zigzagLevelOrder(self, root):
        ans, level, reverse = [], [root], False
        while root and level:
            ans.append([node.val for node in level[::(-1)**reverse]])
            LRpair = [(node.left, node.right) for node in level]
            level = [leaf for LR in LRpair for leaf in LR if leaf]
            reverse = not reverse
        return ans
    

    Solution 2, without the trick, 10 lines

    def zigzagLevelOrder(self, root):
        ans, level, reverse = [], [root], False
        while root and level:
            if reverse:
                ans.append([node.val for node in level][::-1])
            else:
                ans.append([node.val for node in level])
            LRpair = [(node.left, node.right) for node in level]
            level = [leaf for LR in LRpair for leaf in LR if leaf]
            reverse = not reverse
        return ans

Log in to reply
 

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