1. 题目描述
计算给定二叉树的所有左叶子之和。
示例:
3
/ \
9 20
/ \
15 7
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
2. 解题思路
(1)使用递归的话,一下子想不到,先求所有节点的和:
def SumOfTree(self, root):
if not root:
return 0
leave = root.val
left = self.SumOfTree(root.left)
right = self.SumOfTree(root.right)
return left + right + leave
也可以这样写:
def SumOfTree(self, root):
if not root:
return 0
# leave = root.val
left = self.SumOfTree(root.left)
right = self.SumOfTree(root.right)
sum = left + right + root.val
return sum
(2)在求所有节点之和的基础上,再来求所有叶子节点之和:
def SumOfLeave(self, root):
if not root:
return 0
leave = 0
if not root.left and not root.right:
leave = root.val
left = self.SumOfLeave(root.left)
right = self.SumOfLeave(root.right)
return left + right + leave
注意: 一定要初始化 leave,否则会报错UnboundLocalError: local variable 'leave' referenced before assignment
(3)在求所有叶子节点之和的基础上,再来求所有左叶子节点之和:
def SumOfLeftLeave(self, root):
if not root:
return 0
leave = 0
if root.left and not root.left.left and not root.left.right:
leave = root.left.val
left = self.SumOfLeftLeave(root.left)
right = self.SumOfLeftLeave(root.right)
return left + right + leave
上述三种情况可以看出求节点和的套路大体差不多,差别就在于 leave 的取值情况(是取所有节点值,还是取所有的叶子节点值,还是取所有的左叶子节点值),判断的条件也会因此不同。
3. 两种方法
- 方法一:递归
# 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: TreeNode) -> int:
if not root:
return 0
leave = 0
if root.left and not root.left.left and not root.left.right:
leave = root.left.val
left = self.sumOfLeftLeaves(root.left)
right = self.sumOfLeftLeaves(root.right)
return left + right + leave
- 方法二:迭代
利用层次遍历:
(1)判断当前节点的左节点是否存在:若存在,继续判断该节点的左节点是否为叶子节点,若是则加到 res 中;若不是则将该节点的左节点添加进队列。
(2)当前节点右节点则是直接判断存在与否,再考虑是否添加进队列。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if not root:
return 0
queue = deque([root])
res = 0
while queue:
node = queue.popleft()
if node.left:
if node.left and not node.left.left and not node.left.right:
res += node.left.val
else:
queue.append(node.left)
if node.right:
queue.append(node.right)
return res