Simple level tracking with DFS beats 93% in python


  • 0
    D

    Just keep track of levels and update the list as we traverse different levels in DFS

    class Solution(object):
        def answer(self, root, lst, count):
            if(root == None):
                return
            if(len(lst) < count):
                lst.append([root.val])
            else:
                (lst[count-1]).append(root.val)
            self.answer(root.left, lst, count+1)
            self.answer(root.right, lst, count+1)
        
        
        def levelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            lst = []
            count = 0
            if(root == None):
                return lst
            self.answer(root, lst, count+1)
            return lst

Log in to reply
 

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