4 Lines Python Recursive AC Solution

  • 8

    base case => node is none
    recursive case => Left child is / isn't Leave

    class Solution(object):
        def sumOfLeftLeaves(self, root):
            if not root: return 0
            if root.left and not root.left.left and not root.left.right:
                return root.left.val + self.sumOfLeftLeaves(root.right)
            return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)   # isn't leave

    Could be 3 Lines, but L2 would be too long.
    thanks @tototo's advise!

  • 1

    @YJL1228 Thanks for sharing. You can remove the 'else:' line to get a 5-line solution :) Besides, as a best practice, comparison to None should always be done with is or is not. So, if you compare root with None explicitly, we'd better write in this way 'if root is None:', or just simply 'if not root:'.

  • 0

    Similar, but somewhat clearer ... (probably should not indent that deep)

        def sumOfLeftLeaves(self, root):
            def helper(node, isLeft):
                if node:
                    if isLeft and not node.left and not node.right:
                        return node.val # Only returns when isLeft and isLeaf
                    return helper(node.left, True) + helper (node.right, False)
                return 0
            return helper(root, False) # Seems that the OJ doesn't treat bare root as a left leaf

  • 0

    3 lines solution without "too long" line

    def sumOfLeftLeaves(self, root, isLeft=False):
        if not root: return 0
        if not (root.left or root.right): return root.val * isLeft
        return self.sumOfLeftLeaves(root.left, True) + self.sumOfLeftLeaves(root.right)

Log in to reply

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