1 #include
2 #include
3 using namespace std;
4 struct TreeNode {
5 int val;
6 struct TreeNode *left;
7 struct TreeNode *right;
8 };
9
10 class Solution {
11 public:
12 vectorint>> re;//数据成员
13 vectorint> > FindPath(TreeNode* root1, int expectNumber1) {
14 if (root1 == NULL)
15 return re;
16 int count = 0;
17 vector<int> temp;
18 findit(root1,expectNumber1, temp, count);
19 return re;
20 }
21 //在递归函数中不能建立新的变量,可以建立静态变量
22 void findit(TreeNode* root, int expectNumber, vector<int> v2, int countsum)
23 {
24 countsum += root->val;
25 v2.push_back(root->val);//v2用来存储当前vector
26 bool isleaf = root->left == NULL&&root->right == NULL;
27 if (countsum == expectNumber&&isleaf)
28 {
29 //输出这个vector
30 for (int i = 0; i )
31 {
32 cout <" ";
33 }
34 cout << endl;
35 re.push_back(v2);
36 }
37 if (root->left != NULL)
38 findit(root->left, expectNumber,v2, countsum);
39 if (root->right != NULL)
40 findit(root->right, expectNumber, v2, countsum);
41 //v2.pop_back();//如果使用静态变量需要恢复现场
42 }
43
44 };
45
46
47 int main()
48 {
49 // 0 1 2 3 4
50 // {10,5,12,4,7},22
51 TreeNode TreeNode[5];
52 TreeNode[0].val = 10;
53 TreeNode[0].left = &TreeNode[1];
54 TreeNode[0].right = &TreeNode[2];
55
56 TreeNode[1].val = 5;
57 TreeNode[1].left = &TreeNode[3];
58 TreeNode[1].right = &TreeNode[4];
59
60 TreeNode[2].val = 12;
61 TreeNode[2].left = NULL;
62 TreeNode[2].right = NULL;
63
64 TreeNode[3].val = 4;
65 TreeNode[3].left = NULL;
66 TreeNode[3].right = NULL;
67
68 TreeNode[4].val = 7;
69 TreeNode[4].left = NULL;
70 TreeNode[4].right = NULL;
71
72 Solution solu;
73 vectorint> > res = solu.FindPath(&TreeNode[0], 22);
74 cout <<"size = " <endl;
75 /*
76 for (int i = 0; i 77 {
78 for (int j = 0; j 79 {
80 cout <81 }
82 cout <83 }
84 */
85 return 0;
86 }