Efficient Python code 40ms


  • 0
    M

    #approach is storing each level nodes in level variable and processing output. List comprehension makes it easy for us to find nodes in particular level.

    class Solution:
        def zigzagLevelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            level = [root]
            L = []
            left_to_right = True
            while(root and level):
                if left_to_right:
                    L.append([node.val for node in level])
                else:
                    r = []
                    for i in range(len(level)-1,-1,-1):
                        r.append(level[i].val)
                    L.append(r)
                #If we processed left to right next time we should process in reverse order
                if left_to_right:
                    level = [child for node in level for child in (node.left, node.right) if child]
                    left_to_right = False
                else:
                    level = [child for node in level for child in (node.left, node.right) if child]
                    left_to_right = True
            return L
    

Log in to reply
 

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