经典回溯。一招尝遍天下鲜
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> res = new LinkedList();
LinkedList<Integer> path = new LinkedList();
process(root,targetSum,res,path);
return res;
}
public void process(TreeNode root,int targetSum,List<List<Integer>> res, LinkedList<Integer> path){
if(root == null){
return;
}
path.add(root.val);
targetSum-=root.val;
if(targetSum == 0&&root.left == null && root.right == null){
res.add(new LinkedList(path));
}
process(root.left,targetSum,res,path);
process(root.right,targetSum,res,path);
path.removeLast();
}
}