微软算法100题04 二叉树中查找和为某值的所有路径

4.在二元树中找出和为某一值的所有路径
题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如输入整数22 和如下二元树
10
/
5 12
/
4 7
则打印出两条路径:10, 12 和10, 5, 7

思路: 递归  

为了记录路径 需要采用一个辅助数据结构记录正确路径上的节点 这里采用list

1. 从根节点开始 将根节点放入List 将总额sum减去根节点的值 如果等于零 说明找到正确路径上的节点 则打印list

2. 如果该节点有左子树 则用1的逻辑递归处理左子树

3. 如果该节点有右子树 则用1的逻辑递归处理右子树

4. 删除list里的最后一个节点 因为该节点要么为非正确节点 要么为已访问过的正确节点

 1 package com.rui.microsoft;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 public class Test04 {
 7     
 8     
 9     public static void main(String[] args) {
10         Test04 test = new Test04();
11         Node root = test.init();
12         
13         List<Node> list = new ArrayList<Node>();
14         test.findRoute(root, 22, list);
15         
16     }
17     
18     private void findRoute(Node node, int sum, List<Node> list) {
19         list.add(node);
20         sum -= node.value;
21         
22         if(isLeaf(node)){
23             //if sum is zero, it means current node is the last node on the path
24             if(sum == 0) print(list);
25         }else{
26             if(null != node.left){
27                 findRoute(node.left, sum, list);
28             }
29             
30             if(null != node.right){
31                 findRoute(node.right, sum, list);
32             }
33         }
34         
35         //if we reach here, it means current node is not on the path or have already been displayed
36         //remove it
37         //current node is on the top of the list
38         list.remove(list.size()  - 1);
39     }
40     
41     private void print(List<Node> nodes){
42         for(Node node: nodes){
43             System.out.print(" " + node.value);
44         }
45         System.out.println("");
46     }
47 
48     private boolean isLeaf(Node node) {
49         if(null != node.left || null != node.right) return false;
50         return true;
51     }
52 
53     private Node init(){
54         Node left2 = new Node(4,null,null);
55         Node right2 = new Node(7,null,null);
56         Node left = new Node(5,left2,right2);
57         Node right = new Node(12, null, null);
58         Node root = new Node(10,left,right);
59         return root;
60     }
61     
62     class Node {
63         int value;
64         Node left;
65         Node right;
66         
67         public Node(int value){
68             this.value = value;
69         }
70         
71         public Node(int value, Node left, Node right){
72             this.value = value;
73             this.left = left;
74             this.right = right;
75         }
76     }
77 
78 }
原文地址:https://www.cnblogs.com/aalex/p/4896129.html