题目描述: java
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的全部路径。路径定义为从树的根结点开始往下一直到叶结点所通过的结点造成一条路径。 node
输入:每一个测试案例包括n+1行: 测试
第一行为2个整数n,k(1<=n<=10000),n表示结点的个数,k表示要求的路径和,结点编号从1到 n。 this
接下来有n行。这n行中每行为3个整数vi,leftnode,rightnode,vi表示第i个结点的值,leftnode表示第i个结点的左孩子结点编号,rightnode表示第i个结点的右孩子结点编号,若无结点值为-1。编号为1的结点为根结点。 spa
输出:对应每一个测试案例,先输出“result:”占一行,接下来按字典顺序输出知足条件的全部路径,这些路径由结点编号组成,输出格式参照输出样例。 code
样例输入:5 22 10 2 3 5 4 5 12 -1 -1 4 -1 -1 7 -1 -1 1 5 1 -1 -1样例输出:
result: A path is found: 1 2 5 A path is found: 1 3 result:解:首先要想到的是经过遍历能够找到全部路径,按照先序遍历的思路,先将通过的左节点入栈,若是是进的是叶子节点,则判断和是否符合要求,否和要求打印路径将该结点出栈,不否和要求直接将结点出栈,而后继续遍历
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; import java.util.Stack; public class Main { public static int target; static class Node{ public int id; public int data; public Node left; public Node right; public Node(int id){ this.id = id; } } public static Node find(int id, Node node){ if(node != null){ if(node.id == id) return node; Node l = find(id, node.left); Node r = find(id, node.right); if(l != null){ return l; }else if(r != null){ return r; }else return null; }else{ return null; } } public static void search(Node node, Stack<Integer> stack, int sum){ if(node == null || node.id == -1){ return; }else{ sum += node.data; stack.push(node.id); search(node.left, stack, sum); search(node.right, stack, sum); if(sum == target && node.left.id == -1 && node.right.id == -1){ System.out.print("A path is found:"); for(int i:stack){ System.out.print(" "+i); } System.out.println(); } stack.pop(); } } public static void main(String[] args) throws IOException { StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); while(st.nextToken() != StreamTokenizer.TT_EOF){ int n = (int)st.nval; st.nextToken(); Main.target = (int)st.nval; Node root = new Node(1); for(int i = 1; i <= n; i++){ Node node = Main.find(i, root); st.nextToken(); node.data = (int)st.nval; st.nextToken(); int l = (int)st.nval; st.nextToken(); int r = (int)st.nval; if(l > r){ node.left = new Node(r); node.right = new Node(l); }else{ node.left = new Node(l); node.right = new Node(r); } } System.out.println("result:"); Main.search(root, new Stack<Integer>(), 0); } } }
注:第一个案例没经过 get