Python BFS


  • 0
    A
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def zigzagLevelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            if not root:
                return []
            level = 1
            Odd = True
            queue = []
            auxQueue = []
            queue.append(root)
            ans = [[root.val]]
            while queue:
                curr = queue.pop(0)
                if curr.left:
                    auxQueue.append(curr.left)
                if curr.right:
                    auxQueue.append(curr.right)
                if (not queue) and auxQueue:
                    aux = []
                    queue = auxQueue[:]  
                    if Odd:
                        while auxQueue:
                            aux.append(auxQueue.pop().val)
                    else:
                        while auxQueue:
                            aux.append(auxQueue.pop(0).val)
                    ans.append(aux)
                    Odd = not Odd
            return ans
                    
                
            
    

Log in to reply
 

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