Python solution: Another modified level-order traversal


  • 0
    J
    class Solution(object):
        def zigzagLevelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            
            if root is None:
                return []
            
            q = [(root,0)]
            
            levels = {}
            
            while q:
                node, level = q.pop(0)
                
                if level not in levels:
                    levels[level] = [node.val]
                else:
                    levels[level].append(node.val)
                
                if node.left is not None:
                    q.append((node.left,level+1))
                if node.right is not None:
                    q.append((node.right,level+1))
                    
            sortedkeys = sorted(levels.keys())
            
            res = []
            for s in sortedkeys:
                if s%2 == 1:
                    levels[s].reverse()
                res.append(levels[s])
            
            return res

Log in to reply
 

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