my python solution with deque


  • 0
    A
    class Solution(object):
        def zigzagLevelOrder(self, root):
            result = []
            if root == None:
                return result
                
            deque = [root]
            level = 0
            
            while deque:
                collection = []
                level += 1
                size = len(deque)
                
                for _ in range(size):
                    if level % 2 == 0:
                        node = deque.pop()
                        if node.right:
                            deque.insert(0, node.right)
                        if node.left:
                            deque.insert(0, node.left)
                    else:
                        node = deque.pop(0)
                        if node.left:
                            deque.append(node.left)
                        if node.right:
                            deque.append(node.right)
                            
                    collection.append(node.val)
                    
                result.append(collection)
                
            return result
            
        
            
    

Log in to reply
 

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