naive dfs with a dict


  • 0
    X
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    from collections import defaultdict
    
    class Solution(object):
        def internal(self, node, depth):
            if not node:
                return 
            self.ret[depth].append(node.val)
            self.internal(node.left, depth+1)
            self.internal(node.right, depth+1)
        def levelOrderBottom(self, root):
            if not root:
                return []
            self.ret = defaultdict(list)
            self.internal(root, 0)
            #ret: {int:[int]}
            items = self.ret.items()
            items.sort(key= lambda p:p[0], reverse=True)
            return zip(*items)[1]
            
    

    the dict is not necessary. by changing Solution.internal method we can use a simple list to store the values with a little more ifs.


Log in to reply
 

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