題目描述:
輸入一顆二叉樹和一個整數,打印出二叉樹中結點值的和爲輸入整數的所有路徑。路徑定義爲從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。
輸入:
每個測試案例包括n+1行:
第一行爲2個整數n,k(1<=n<=10000),n表示結點的個數,k表示要求的路徑和,結點編號從1到n。
接下來有n行。這n行中每行爲3個整數vi,leftnode,rightnode,vi表示第i個結點的值,leftnode表示第i個結點的左孩子結點編號,rightnode表示第i個結點的右孩子結點編號,若無結點值爲-1。編號爲1的結點爲根結點。
輸出:
對應每個測試案例,先輸出“result:”佔一行,接下來按字典順序輸出滿足條件的所有路徑,這些路徑由結點編號組成,輸出格式參照輸出樣例。
代碼:
package JvavaDataTest;
import java.util.LinkedList;
import java.util.List;
public class FindPathTest {
public static void main(String[] args) {
Node root = new Node(8);
Node node8 = new Node(8);
Node node7 = new Node(7);
root.left = node8;
root.right = node7;
Node node9 = new Node(9);
node8.left = node9;
Node node2 = new Node(2);
node8.right = node2;
Node node4 = new Node(4);
Node node72 = new Node(7);
node2.left = node4;
node2.right = node72;
findpath(root,15);
}
public static void findpath(Node root,int expect){
if(root == null){
return;
}
List<Node> path = new LinkedList<Node>();
int currentSum = 0;
findPath(root, expect, path, currentSum);
}
private static void findPath(Node node,int expect,List<Node> path,int currentSum){
currentSum += node.key;
path.add(node);
if(node.left == null && node.right == null && currentSum == expect){
System.out.println("路徑已經找到");
for(Node n : path){
System.out.print(n.key +" ");
}
System.out.println("");
}
if(node.left != null){
findPath(node.left,expect,path,currentSum);
}
if(node.right != null){
findPath(node.right,expect,path,currentSum);
}
path.remove(path.size()-1);
}
}
class Node{
int key;
Node left;
Node right;
Node(int key){
this.key = key;
}
}
結果: