题目:给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。
思路:使用二叉树前序递归遍历,加上回溯法。
class Solution {
List<List<Integer>> arrays = new ArrayList<List<Integer>>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
if(root==null){
return null;
}
ArrayList<Integer> array = new ArrayList<Integer>();
helpSum(array, root, targetSum);
return arrays;
}
public void helpSum(ArrayList<Integer> array, TreeNode root, int target){
if(root==null){
return;
}
array.add(root.val);
if(root.left==null&&root.right==null&&target==root.val){
arrays.add(new ArrayList<Integer>(array));
}
helpSum(array, root.left, target-root.val);
helpSum(array, root.right, target-root.val);
array.remove(array.size()-1);
}
}