Simple Python solution using dict


  • 8
    class Solution(object):
        def findLeaves(self, root):
            def order(root, dic):
                if not root:
                    return 0
                left = order(root.left, dic)
                right = order(root.right, dic)
                lev = max(left, right) + 1
                dic[lev] += root.val,
                return lev
            dic, ret = collections.defaultdict(list), []
            order(root, dic)
            for i in range(1, len(dic) + 1):
                ret.append(dic[i])
            return ret

  • 0
    X

    I think dic[lev] += root.val should be dic[lev].append(root.val)?


  • 0
    R

    @xinyao There is a comma ',' after root.val which is equivalent to append


  • 0
    W

    the last three lines can be replaced with:

    return [dic[key] for key in sorted(dic)]


  • 0

    after few different implementations, I ended up implementing almost the exact same thing as yours :D

    I tried OrderedDict as well so I don't need sort at the end, but list appending for that is more complicated than defaultdict. Sadly we don't have OrderedDefaultDict that would make this even simpler.


  • 0
    L

    @wonderfuly You're increasing the runtime, why would he do that?


  • 0
    W

    @livelearn because readability counts


Log in to reply
 

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