这个题的意思就是在二叉排序树中找到所有使得和为指定值的路径,需要注意的一点是,树中的路径指的是从树的根节点到任一叶子结点的路径,也就是说如果这条路径的结尾不是叶子节点,即使值等于给定值,也是不存在路径的,这个题从看到题意的第一反应就是利用回溯,首先深度遍历一条路径,如果该路径不符合条件,则回溯到父亲节点,遍历父亲节点的另一条路径,直到整个树遍历完成,在这个过程中,需要一个栈来保存当前已访问的节点,主要是为了记录已访问的值,具体代码如下:

   1 import java.util.*;

 2 class Node{
 3     public Node(int val){
 4         this.val = val;
 5     }
 6     int val;
 7     Node left;
 8     Node right;
 9 }
10 
11 public class TreePath{
12     Stack<Integer> stack = new Stack<Integer>();
13     public void pathes(Node root,int count,int des){
       if(root==null){
          return;
       }
14 if(root.val+count < des){ 15 //如果当前值小于目标值,则添加这个节点的值,然后继续访问其左子树和右子树。 16 count+=root.val; 17 stack.push(root.val); 18 }else if(root.val+count==des){ 19 //如果当前节点值加上已有的值正好等于目标值,且该节点为叶子节点,则输出这个序列,然后将棧顶的元素弹出,返回上一层。 20 if(root.left==null&&root.right==null){ 21 stack.push(root.val); 22 for(int i=0;i<stack.size();i++){ 23 System.out.print(stack.get(i) +" "); 24 } 25 System.out.println(); 26 stack.pop(); 27 return; 28 }else{ 29 //如果当前节点不是叶子节点,那么就不能算找到了,而且后续的访问肯定大于目标值,就不需要访问了,直接返回上一层 30 return; 31 } 32 }else if(root.val+count>des){ 33 return; 34 } 35 if(root.left!=null){ 36 pathes(root.left,count,des); 37 } 38 if(root.right!=null){ 39 pathes(root.right,count,des); 40 } 41 stack.pop(); 42 count -=root.val; 43 } 44 45 public static void main(String [] args){ 46 Node root = new Node(10); 47 Node l1 = new Node(5); 48 Node l2 = new Node(4); 49 Node l3 = new Node(7); 50 Node l4 = new Node(12); 51 root.left = l1; 52 root.right = l4; 53 l1.left = l2; 54 l1.right = l3; 55 TreePath tp = new TreePath(); 56 tp.pathes(root,0,15); 57 } 58 }