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

题目:输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

 

开始打算用循环和栈,类似深度遍历的方法,但是不容易处理删除路径上不满足要求的结点,后来想到了这种向左右子树的递归的方法,发现和答案一样,呵呵。。。

 1 /**
 2      * 此种递归不需要返回值,但是需要在结束之前作出修改
 3      * @param root 根结点
 4      * @param list 路径
 5      * @param sum 要求的路径和
 6      */
 7     public static void getPath(BinaryTreeNode<Integer> root, ArrayList<Integer> list, int sum){
 8         
 9         BinaryTreeNode<Integer> left = root.leftChildTree;
10         BinaryTreeNode<Integer> right = root.rightChildTree;
11         
12         
13         int tempSum = 0;
14         list.add(root.key);
15         /* 如果是叶子结点*/
16         if (null == left && null == right) {
17             for (int i = 0; i < list.size(); i++) {
18                 tempSum += list.get(i);
19             }
20             if (tempSum == sum) {
21                 for (int i = 0; i < list.size(); i++) {
22                     System.out.print(list.get(i) + " ");
23                 }
24                 System.out.println();
25             }
26         } else {
27             if (left != null) {
28                 getPath(left, list, sum);
29             }
30             
31             if (right != null) {
32                 getPath(right, list, sum);
33             }
34         }
35         /* 在返回到父结点之前,在路径上删除当前结点  */
36         list.remove(list.size()-1);
37         
38     }

 

posted @ 2014-09-11 20:48  soul390  阅读(470)  评论(0)    收藏  举报