题目
给定一颗二叉树,返回它所有左叶子节点之和
举例
3
/ \
9 20
/ \
15 7
return 24
递归方法
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if not root.left and not root.right: #当前节点不存在左右子树
return 0
if not root.left and root.right: #当前节点只有右子树
return self.sumOfLeftLeaves(root.right)
if root.left and not root.right: #当前节点只有左子树
if not root.left.left and not root.left.right: #当前节点的左节点不存在左右子树
return root.left.val
else:
return self.sumOfLeftLeaves(root.left)
sum = 0
if root.left and root.right: #当前节点既有左子树又有右子树
if not root.left.left and not root.left.right: #当前节点的左子树没有左右节点
sum += root.left.val
else:
sum += self.sumOfLeftLeaves(root.left)
sum += self.sumOfLeftLeaves(root.right)
return sum
简化递归写法(参考他人)
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
sum = 0
if root.left and not root.left.left and not root.left.right:
sum += root.left.val
sum += self.sumOfLeftLeaves(root.left)
sum += self.sumOfLeftLeaves(root.right)
return sum