Python Solution using Dictionary


  • 0
    D
    from collections import defaultdict
    class Solution(object):
        def levelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            
            dd = defaultdict(list)
            
            self.LO(root,dd)
            
            sol = []
            for i in range(len(dd)):
                sol.append(dd[i])
            
            return sol
        
        def LO(self,root,dd,depth=0):
            if not root:
                return []
            
            dd[depth].append(root.val)
            
            self.LO(root.left,depth=depth+1,dd=dd)
            self.LO(root.right,depth=depth+1,dd=dd)
    

Log in to reply
 

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