Skip to content

404 sum of left leaves

404. Sum of Left Leaves

题目: https://leetcode.com/problems/sum-of-left-leaves/

难度: Easy

思路:

典型递归,检查root的左孩子是不是node,是的话加上它的值,不是的话递归去求它的孩子们的,对于右边,递归的求sum of left leaves

class Solution(object):
    def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def isLeaf(node):
            if node == None:
                return False
            if node.left == None and node.right == None:
                return True
            return False

        res = 0

        if root:
            if isLeaf(root.left):
                res += root.left.val
            else:
                res += self.sumOfLeftLeaves(root.left)
            if root.right:
                res += self.sumOfLeftLeaves(root.right)

        return res


回到顶部