品牌的手机网站制作,清新大气企业公司网站源码,next 主题wordpress,短视频剪辑哪里学输入一颗二叉树和一个整数#xff0c;打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
代码#xff1a;
package offer;
import java.util.ArrayList;
class BineryTree1 { int val; Bine…输入一颗二叉树和一个整数打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
代码
package offer;
import java.util.ArrayList;
class BineryTree1 { int val; BineryTree1 left null; BineryTree1 right null; BineryTree1(int val) { this.val val; } } public class ti34 { static ArrayListInteger list new ArrayListInteger(); static ArrayListArrayListInteger result new ArrayListArrayListInteger(); static ArrayListArrayListInteger FindPath(BineryTree1 root,int target) { if(rootnull) { return result; } list.add(root.val); target-root.val; if(target 0 root.left null root.right null) { result.add(new ArrayListInteger(list) );//重点这里一定要强制new一个对象要不然不行 } FindPath(root.left,target); FindPath(root.right,target); list.remove(list.size()-1); return result; } public static void main(String[] args) { BineryTree1 a new BineryTree1(10); BineryTree1 b new BineryTree1(5); BineryTree1 c new BineryTree1(12); BineryTree1 d new BineryTree1(4); BineryTree1 e new BineryTree1(7); a.left b; a.right c; b.left d; b.right e; ArrayListArrayListInteger list FindPath(a,22); for(int i0;ilist.size();i) { for(int j0;jlist.get(i).size();j) { System.out.print(list.get(i).get(j) ); } System.out.println(); } } }