Share my python solution


  • 0
    Y
    class Solution(object):
        def zigzagLevelOrder(self, root):
            queue=collections.deque([(root,1)])
            dic=collections.defaultdict(list)
            res=[]
            while queue:
                root,level=queue.popleft()
                if not root:continue
                dic[level].append(root.val)
                if root.left:queue.append((root.left,level+1))
                if root.right:queue.append((root.right,level+1))
            for key in sorted(dic):
                if key%2:
                    res.append(dic[key])
                else:
                    res.append(dic[key][::-1])
            return res
    

Log in to reply
 

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