题目链接
思路
递归查询;再查询的过程中记录所走的路径 每走一步判断当前是否是叶子节点,以及路径和是否与target相等
满足条件就加入到结果里面 不满足条件就继续递归,直至递归到叶子节点 每次结束需要回退到父节点时,要把记录的当前的路径给清除掉
java
public List < List < Integer > > pathSum ( TreeNode root, int target) {
List < List < Integer > > res = new LinkedList < > ( ) ;
LinkedList < Integer > path = new LinkedList < > ( ) ;
pathSum ( root, target, 0 , path, res) ;
return res;
}
public void pathSum ( TreeNode root, int target, int currentSum, LinkedList < Integer > path, List < List < Integer > > res) {
if ( root == null ) {
return ;
}
path. add ( root. val) ;
currentSum += root. val;
if ( currentSum == target && root. left == null && root. right == null ) {
res. add ( new LinkedList < > ( path) ) ;
}
pathSum ( root. left, target, currentSum, path, res) ;
pathSum ( root. right, target, currentSum, path, res) ;
path. removeLast ( ) ;
}
go
func pathSum ( root * TreeNode, target int ) [ ] [ ] int {
var res [ ] [ ] int
var path [ ] int
sumPath ( root, target, 0 , & res, & path)
return res
}
func sumPath ( root * TreeNode, target, currentSum int , res * [ ] [ ] int , path * [ ] int ) {
if root == nil {
return
}
* path = append ( * path, root. Val)
currentSum += root. Val
if currentSum == target && root. Left == nil && root. Right == nil {
var path1 [ ] int
path1 = append ( path1, * path... )
* res = append ( * res, path1)
}
sumPath ( root. Left, target, currentSum, res, path)
sumPath ( root. Right, target, currentSum, res, path)
* path = ( * path) [ : len ( * path) - 1 ]
}