Python easy to understand


  • 0
    J

    The basic idea is to use a boolean flag and to reverse the temp array received every time the flag is true. Start with flag as false as we need to reverse the order from the point we get to the children of the root

    class Solution:
        def zigzagLevelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            result = []
            if (root is None):
                return result 
            levels = [root]
            flag = False
            while levels:
                temp = []
                nextLevel = []
                while levels:
                    node = levels.pop(0)
                    temp.append(node.val)
                    if node.left:
                        nextLevel.append(node.left)
                    if node.right:
                        nextLevel.append(node.right)
                if (flag):
                    temp = temp[::-1]
                flag = not flag
                levels = nextLevel
                if temp:
                    result.append(temp)
            return result
    
    

Log in to reply
 

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