my accepted simple python solution basis level traverse


  • 0
    N

    The same with level traverse that I use a queue to put nodes of every level, and use a bool variable to decide if should reverse the list value of current level
    '''
    import Queue

    class Solution(object):
    def zigzagLevelOrder(self, root):
    ret = []
    if not root:
    return ret
    queue = Queue.Queue()
    queue.put(root)
    shouldreverse = False

        while not queue.empty():
            nodevals = []
            size = queue.qsize()
            for _ in xrange(size):
                node = queue.get()
                nodevals.append(node.val)
                if node.left:
                    queue.put(node.left)
                if node.right:
                    queue.put(node.right)
            if shouldreverse:
                nodevals = nodevals[::-1]
            shouldreverse = not shouldreverse
            ret.append(nodevals)
        
        return ret
    

    ''''


Log in to reply
 

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