递归 回溯
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int expectNumber) {
if(root == null){
return new ArrayList<ArrayList<Integer>>() ;
}
Deque<Integer> deque = new LinkedList<Integer>();
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
dfs(root,expectNumber,res,deque);
return res;
}
public void dfs(TreeNode root,int target,ArrayList<ArrayList<Integer>> res,Deque<Integer> deque){
if(root == null){
return ;
}
deque.addLast(root.val);
target -=root.val;
if(root.left == null && root.right ==null && target == 0 ){
ArrayList<Integer> arr = new ArrayList<Integer>(deque);
res.add(arr);
}
dfs(root.left,target,res,deque);
dfs(root.right,target,res,deque);
deque.pollLast();
}
}