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.left != None and root.left.left == None and root.left.right == None
- 当在左子树上找到左叶子后(比如例子中的 9),还需要在右子树上找到左叶子之和(递归),并且相加。用代码表示为
root.left.val + self.sumOfLeftLeaves(root.right)
- 如果当前结点的左子树不是叶子,则递归求左右子树的左子树之和。用代码表示为
self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
Python 实现:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
if root.left != None and root.left.left == None and root.left.right == None:
return root.left.val + self.sumOfLeftLeaves(root.right) # 左叶子加上在右子树中求左叶子之和
return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right) # 求左右子树中左叶子之和