Python DFS accepted solution


  • 0
    G

    class Solution:
    # @param root, a tree node
    # @return a list of lists of integers

    def levelOrder(self, root):
        self.level_order_list = []
        self.dfs_traverse(root, l = 0)
        return self.level_order_list
    
    def dfs_traverse(self, root, l):
        if not root:
            return
        if len(self.level_order_list) == l or l == 0:
            # List does not have the level
            self.level_order_list.append([root.val])
        elif len(self.level_order_list) >= l + 1:
            # List has the level
            self.level_order_list[l].append(root.val)
        self.dfs_traverse(root.left, l + 1)
        self.dfs_traverse(root.right, l + 1)

Log in to reply
 

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