Easy Python recursive solution


  • 3
    class Solution(object):
        def sumOfLeftLeaves(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            sum = 0
            if not root:
                return 0
            if root.left and not root.left.left and not root.left.right:
                sum += root.left.val
            sum += self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
            return sum
    

  • 0

    @Helly0000 I am new to Python. Could anybody let me know what is wrong with my code? Thanks!

    class Solution(object):
    def sumOfLeftLeaves(self, root):
    """
    :type root: TreeNode
    :rtype: int
    """

        def sumLeaves(root, sum):
            if not root:
                return sum
            if not root.left:
                sum += root.left.val
                sum += sumLeaves(root.left, sum)
            if not root.right:
                sum += sumLeaves(root.right, sum)
            return sum
        
        return sumLeaves(root, 0)

Log in to reply
 

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