
1 View Code
2 #include <iostream>
3 #include <vector>
4 using namespace std;
5
6
7 struct BinaryTreeNode
8 {
9 int m_nValue;
10 BinaryTreeNode * m_pLeft;
11 BinaryTreeNode * m_pRight;
12 };
13
14
15 void print(vector<int> & v)
16 {
17 for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
18 {
19 cout<<*it<<" ";
20 }
21 cout<<endl;
22 }
23
24
25 void travel(BinaryTreeNode * root, vector<int> &v, int total, int ¤t)
26 {
27 if(root==NULL)
28 {
29 return;
30 }
31 v.push_back(root->m_nValue);
32 current += root->m_nValue;
33
34
35 if (current == total)
36 {
37 print(v);
38 }
39
40
41 if (root->m_pLeft != NULL)
42 {
43 travel(root->m_pLeft, v, total, current);
44 }
45 if (root->m_pRight != NULL)
46 {
47 travel(root->m_pRight, v, total, current);
48 }
49
50
51 v.pop_back();
52 current -= root->m_nValue;
53 }
54
55
56 BinaryTreeNode * buildnode(int num = 0, BinaryTreeNode * left = NULL, BinaryTreeNode * right = NULL)
57 {
58 BinaryTreeNode * res = new BinaryTreeNode();
59 res->m_nValue = num;
60 res->m_pLeft = left;
61 res->m_pRight = right;
62 return res;
63 }
64
65
66 int main()
67 {
68 BinaryTreeNode * root = buildnode(10, buildnode(5, buildnode(4), buildnode(7, buildnode(3, NULL, buildnode(-3)))), buildnode(12));
69 vector<int> v;
70 int total = 22;
71 int current = 0;
72 travel(root, v, total, current);
73 return 0;
74 }