输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
代码:
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 ArrayList<Integer> list = new ArrayList<Integer>();
     static ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
     static  ArrayList<ArrayList<Integer>> FindPath(BineryTree1 root,int target)
     {
         
         if(root==null)
         {
             return result;
         }
         list.add(root.val);
         target-=root.val;
         if(target == 0 && root.left == null && root.right == null) {
             result.add(new ArrayList<Integer>(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;
         ArrayList<ArrayList<Integer>> list = FindPath(a,22);
         for(int i=0;i<list.size();i++)
         {
             for(int j=0;j<list.get(i).size();j++)
             {
                 System.out.print(list.get(i).get(j)+" ");
             }
             System.out.println();
         }
     }
 }