Python Simple Recursion


  • 0
    S
    def levelOrderBottom(self, root):
        if not root:
            return []
    
        level_dict = {}
    
        def reverse_tree(r, level):
            if not r:
                return
    
            if level in level_dict:
                level_dict[level].append(r.val)
            else:
                level_dict[level] = [r.val]
            # print(level_dict)
    
            if r.left:
                reverse_tree(r.left, level+1)
    
            if r.right:
                reverse_tree(r.right, level+1)
    
        reverse_tree(root, 0)
    
        bottom_up_lst = [level_dict[l] for l in sorted(level_dict, reverse=True)]
    
        return bottom_up_lst

Log in to reply
 

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