topic:
An input binary tree root node and an integer, the binary print values of nodes in the input path and all integers. Forming a path to the path definition begins from the root node of the tree down to the leaf node has been traversed nodes. (Note: the return value in the list, a large array Array front)
answer:
Recursively, as follows:
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
ArrayList<Integer> list = new ArrayList<>();
if(root==null){
return result;
}
list.add(root.val);
recursive(root,target,result,list);
return result;
}
public void recursive(TreeNode root,int target,ArrayList<ArrayList<Integer>> result,ArrayList<Integer> list){
if(root.val==target&&root.left==null&&root.right==null){
result.add(list);
}
if(root.left!=null){
ArrayList<Integer> leftList = new ArrayList<>();
leftList.addAll(list);
leftList.add(root.left.val);
recursive(root.left,target-root.val,result,leftList);
}
if(root.right!=null){
ArrayList<Integer> rightList = new ArrayList<>();
rightList.addAll(list);
rightList.add(root.right.val);
recursive(root.right,target-root.val,result,rightList);
}
}
}