二叉树中和为某一值的路径

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
 1 import java.util.ArrayList;
 2 import java.util.Stack;
 3 public class Solution {
 4     public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,
 5             int target) {
 6         ArrayList<ArrayList<Integer>> pathList=
 7                 new ArrayList<ArrayList<Integer>>();
 8         if(root==null)
 9             return pathList;
10         Stack<Integer> stack=new Stack<Integer>();
11         FindPath(root,target,stack,pathList );
12         return pathList;
13          
14     }
15     private void FindPath(TreeNode root, int target,
16             Stack<Integer> path,
17             ArrayList<ArrayList<Integer>> pathList) {
18         if(root==null)
19             return;
20         if(root.left==null&&root.right==null){
21             if(root.val==target){
22                 ArrayList<Integer> list=
23                         new ArrayList<Integer>();
24                 for(int i:path){
25                     list.add(new Integer(i));
26                 }
27                 list.add(new Integer(root.val));
28                 pathList.add(list);
29             }
30         }
31         else{
32             path.push(new Integer(root.val));
33             FindPath(root.left, target-root.val, path, pathList);
34             FindPath(root.right, target-root.val, path,  pathList);
35             path.pop();
36         }
37          
38     }
39 }

这个代码不太懂!

原文地址:https://www.cnblogs.com/LoganChen/p/6432895.html