来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-ii
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
解题思路:这道题是LeetCode上一道题的加强版,但是总体的思路其实变化不大,我们可以考虑用一个列表来存储到达每个节点的路径,当到达叶子节点的时候读取对应列表并求和,然后判断是够满足条件。AC代码如下:
class Solution(object): def pathSum(self, root, sum): """ :type root: TreeNode :rtype: int """ if not root: return [] queue_root = [] result = [] queue_root.append([[root.val], root]) # 设置到达每个节点的路径和 while queue_root: value, node = queue_root.pop(0) if not node.left and not node.right: # 判断是否满足条件 temp_sum = sum_list(value) if temp_sum == sum: result.append(value) if node.left: queue_root.append((value + [node.left.val], node.left)) # 注意此处不能使用append方法,因为该方法是浅拷贝,导致每个节点的列表其实是同一个列表 if node.right: queue_root.append((value + [node.right.val], node.right)) return result def sum_list(value): result = 0 for i in value: result += i return result