package java2019;
//二叉树中和为某值的路径 从根节点到叶子节点
import java.util.ArrayList;
public class Demo22 {
static ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();
static ArrayList<Integer> list = new ArrayList<Integer>();
public static ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target){
if (root == null){
return null;
}
list.add(root.val);
target -= root.val;
if(target==0&&root.left==null&&root.right==null)
listAll.add(new ArrayList<Integer>(list));
FindPath(root.left,target);
FindPath(root.right, target);
list.remove(list.size()-1);
return listAll;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
TreeNode n1 = new TreeNode(3);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(7);
TreeNode n4 = new TreeNode(8);
root.left=n1;
root.right=n2;
n1.left=n3;
n2.right=n4;
listAll=FindPath(root,11);
for(ArrayList<Integer> a:listAll){
for(int i:a){
System.out.print(i+"--");
}
System.out.println();
}
}
}
22.二叉树中和为某值的路径 从根节点到叶子节点
最新推荐文章于 2021-07-07 18:04:25 发布