Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.
For example:
Given the below binary tree and sum = 22
,
5 / 4 8 / / 11 13 4 / \ / 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
题目大意:给定一棵二叉树和一个总和,找出所有从根节点到叶节点的路径上所有节点的值之和等于给定总和的路径集合
解题思路:该题目跟上一题PATH SUM非常相似,只不过上一题只需判断是否存在符合条件的路径,而该题需要将符合条件的路径输出,难度加大了。解题的思路是,像上一题一样遍历整棵树,每走一步,就先用sum减掉父节点的值,然后这里要多做一步就是把父节点的值加入到当前路径中。最后到了叶子节点的时候,判断当前sum是否等于叶子节点的值,如果相等的话,说明该条路径是符合要求的路径,把叶子节点的值也加入当前路径中然后输出。
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
A=[]
def haspathSum(root, sum, path):
if root == None:
return A
if sum == root.val and root.left == None and root.right == None:
return A + [path + [root.val]]
else:
return haspathSum(root.left, sum - root.val, path + [root.val]) + haspathSum(root.right, sum - root.val, path + [root.val])
return haspathSum(root, sum, [])