Simple Python solution using dict

  • 9
    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):
            return ret

  • 0

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

  • 1

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

  • 1

    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

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

  • 0

    @livelearn because readability counts

Log in to reply

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