Skip to content

Latest commit

 

History

History
48 lines (38 loc) · 1.49 KB

0404. Sum of Left Leaves.md

File metadata and controls

48 lines (38 loc) · 1.49 KB

题目

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.

我的思路

这道题要求所有左节点的和,依然用递归来做,只不过递归终止的条件比较麻烦:只有在当前root左子树的左子树不存在时,才取root左子树的值,其他情况一律不取值。

class Solution:
    def sumOfLeftLeaves(self, root: TreeNode) -> int:
        if not root:
            return 0
        if not root.left and not root.right:
            return 0
        if not root.left:
            return self.sumOfLeftLeaves(root.right)
        if not root.left.left and not root.left.right:
            return root.left.val + self.sumOfLeftLeaves(root.right)
        else:
            return self.sumOfLeftLeaves(root.left)+self.sumOfLeftLeaves(root.right)

看了别人更快的方法,在给定的函数上做了修改,增加了一个isLeft参数来告知传入该函数的节点是否为左子树,这样其实就容易得多。

class Solution:
    def sumOfLeftLeaves(self, root: TreeNode, isLeft=False) -> int:
        if not root:
            return 0
        if  root.left is None and root.right is None and isLeft:
            return root.val
        return self.sumOfLeftLeaves(root.left,isLeft =True)\
    + self.sumOfLeftLeaves(root.right,isLeft =False)