Modified BFS solution


  • 0
    R
    class Solution(object):
        def zigzagLevelOrder(self, root):
            if not root:
                return []
            rlist = [[root.val]]
            frontier = [root]
            i = 1
            while frontier:
                next = []
                for node in frontier:
                    if node:
                        next.append(node.left)
                        next.append(node.right)
                frontier = next
                tmpNext = []
                if (i%2):
                    for c in reversed(next):
                        if c:
                            tmpNext.append(c.val)
                else:
                    for c in next:
                        if c:
                            tmpNext.append(c.val)
                if tmpNext:                        
                    rlist.append(tmpNext)
                i += 1
                        
            return (rlist)
    

Log in to reply
 

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