A clear Python recursive solution

  • 0

    Define a wrapper function and use a flag to label the left leaves. Then the rest is straightforward.

    def sumOfLeftLeaves(self, root):
        def f(root, flag):
            if root is None: return 0
            if root.left is None and root.right is None:
                if flag:
                    return root.val
                    return 0
            return f(root.left, True) + f(root.right, False)
        return f(root, False)

Log in to reply

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