Short and clear python code


  • 3
    T
    class Solution:
    # @param root, a tree node
    # @return a list of lists of integers
    def zigzagLevelOrder(self, root):
        queue = collections.deque([root])
        res = []
        while queue:
            r = []
            for _ in range(len(queue)):
                q = queue.popleft()
                if q:
                    r.append(q.val)
                    queue.append(q.left)
                    queue.append(q.right)
            r = r[::-1] if len(res) % 2 else r
            if r:
                res.append(r)
        return res

  • 0

    Mine is very similar

    from collections import deque
    class Solution:
        # @param root, a tree node
        # @return a list of lists of integers
        def zigzagLevelOrder(self, root):
            queue = deque()
            queue.append(root)
            switch = True #left to right
            ans = []
            if (root):
                while(queue):
                    level = []
                    for i in range(len(queue)):
                        node = queue.popleft()
                        level.append(node.val)
                        self.appendNode(queue, node.left)
                        self.appendNode(queue, node.right)
                        
                    if (not switch):
                        level.reverse()
                        
                    ans.append(level)
                    switch = not switch
            return ans
            
        def appendNode(self, queue, node):
            if (node):
                queue.append(node)

  • 0
    H

    I like this deque solution. although it may not be what they want. And there some extra cost of reversing. However, it is indeed much clear and concise.


Log in to reply
 

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