Python simple BFS


  • 17
    F

    Simple straightforward solution using flag to decide whether from left to right or from right to left

    class Solution(object):
    def zigzagLevelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root: return []
        res, temp, stack, flag=[], [], [root], 1
        while stack:
            for i in xrange(len(stack)):
                node=stack.pop(0)
                temp+=[node.val]
                if node.left: stack+=[node.left]
                if node.right: stack+=[node.right]
            res+=[temp[::flag]]
            temp=[]
            flag*=-1
        return res

  • 0
    E

    Using one stack and avoiding creating new list speeds up the code a lot! The flag is brilliant too!!


  • 0
    S

    This is essentially a queue, since you are adding to end and removing from front.


  • 0
    T
    This post is deleted!

Log in to reply
 

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