[九度][何海涛] 二叉树中和为某一值的路径

题目描述:

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

输入:

每个测试案例包括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:”占一行,接下来按字典顺序输出满足条件的所有路径,这些路径由结点编号组成,输出格式参照输出样例。

样例输入:
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:

OJ有一点不爽就是你明知道答案是对的,但格式不对害死人。这题就是一道树的遍历,注意的是左右子树的顺序,有可能做子树编号大于右子树的,所以先要判断一下,遍历编号小的。
 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 struct Node
 6 {
 7     int val;
 8     int left, right;
 9 };
10 
11 Node node[10001];
12 
13 void print(int index, int sum, int needSum, vector<int> path)
14 {
15     path.push_back(index);
16 
17     if (index == -1)
18         return;
19 
20     sum += node[index].val;
21 
22     if (node[index].left == -1 && node[index].right == -1)
23     {
24         if (sum == needSum)
25         {
26             cout << "A path is found:";
27             for(int i = 0; i < path.size(); i++)
28                 cout << " " << path[i];
29             cout << endl;
30         }
31         return;
32     }
33 
34     if (node[index].left < node[index].right)
35     {
36         print(node[index].left, sum, needSum, path);
37         print(node[index].right, sum, needSum, path);
38     }
39     else
40     {
41         print(node[index].right, sum, needSum, path);
42         print(node[index].left, sum, needSum, path);
43     }
44 }
45 
46 int main()
47 {
48     int n, sum;
49     while(cin >> n >> sum)
50     {
51         for(int i = 1; i <= n; i++)
52             cin >> node[i].val >> node[i].left >> node[i].right;
53 
54         vector<int> path;
55         cout << "result:" << endl;
56         print(1, 0, sum, path);
57     }
58 }
原文地址:https://www.cnblogs.com/chkkch/p/2780730.html