Skip to content

Latest commit

 

History

History
60 lines (42 loc) · 1.22 KB

0404._sum_of_left_leaves.md

File metadata and controls

60 lines (42 loc) · 1.22 KB

404. Sum of Left Leaves

难度: Easy

刷题内容

原题连接

内容描述


Find the sum of all left leaves in a given binary tree.

Example:

    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

解题方案

思路 1 - 时间复杂度: O(N)- 空间复杂度: O(1)******

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

class Solution(object):
    def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def isLeaf(node):
            if not node:
                return False
            if not node.left and not node.right:
                return True
            return False
        
        res = 0
        if root:
            if isLeaf(root.left):
                res += root.left.val
            else:
                res += self.sumOfLeftLeaves(root.left)
            res += self.sumOfLeftLeaves(root.right)
        return res