Simple, short & clean Python recursive solution with explanation

  • 1

    Base case (node is None) -> return 0
    Return sum of:

    • sumOfLeftLeaves of left node
    • sumOfLeftLeaves of right node
    • left node value if it is a leaf
    class Solution(object):
        def sumOfLeftLeaves(self, root):
            if not root:
                return 0
            sum =  self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
            if root.left and not root.left.left and not root.left.right:
                sum += root.left.val
            return sum

Log in to reply

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