// recursive it, but on the condition recursion in the end to be a good judge, for example, is the full path to the leaf node, that is to say about the child nodes are empty, and this time root.val == target represents a list found , and then return.
But because I did not use directly on the target-root.val, so in some cases, for example, encountered a null node, we can not directly return, you need to add a value to the list, because then return to the previous level we will remove out of the last element in the list, so every time we have a recursive time to add a list of elements, or return to the previous level when the node elements that do not, this is a point to note,
There is, if it is not a leaf node, and this time root.val> = target, that is, below the else, we can not continue to recursively go directly back on it,
** Or you can come directly to the val value to be knocked off, so sometimes you do not need to list the value of adding a insignificant, but this is the end of the target == 0.
1 import java.util.ArrayList; 2 /** 3 public class TreeNode { 4 int val = 0; 5 TreeNode left = null; 6 TreeNode right = null; 7 8 public TreeNode(int val) { 9 this.val = val; 10 11 } 12 13 } 14 */ 15 public class Solution { 16 ArrayList<ArrayList<Integer>> res=new ArrayList<>(); 17 public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) { 18 ArrayList<Integer> list=new ArrayList<>(); 19 if(root==null) 20 return res; 21 helper(root,target,list); 22 return res; 23 } 24 public void helper(TreeNode root, int target,ArrayList<Integer> list) 25 { 26 if(root==null) 27 { 28 list.add(0); 29 return ; 30 } 31 if(root.left==null&&root.right==null) 32 { 33 if(root.val==target) 34 { 35 list.add(root.val); 36 res.add(new ArrayList<Integer>(list)); 37 return ; 38 } 39 else 40 { 41 list.add(0); 42 return ; 43 } 44 } 45 if(root.val<target) 46 { 47 list.add(root.val); 48 helper(root.left,target-root.val,list); 49 list.remove(list.size()-1); 50 helper(root.right,target-root.val,list); 51 list.remove(list.size()-1); 52 } 53 else 54 { 55 list.add(0); 56 return ; 57 } 58 return ; 59 60 } 61 }