-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest34.cpp
114 lines (90 loc) · 1.78 KB
/
test34.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct TreeNode
{
int key;
struct TreeNode *LeftChild;
struct TreeNode *RightChild;
};
TreeNode *insert(TreeNode *root,double key)
{
if(!root)
{
TreeNode *newnode=new TreeNode;
newnode->key=key;
newnode->LeftChild=nullptr;
newnode->RightChild=nullptr;
root=newnode;
return root;
}
if(key>root->key) root->RightChild=insert(root->RightChild,key);
else if(key<root->key) root->LeftChild=insert(root->LeftChild,key);
return root;
}
void PrintLevel(TreeNode *root,int level)
{
if(!root) return;
if(level<1) return;
if(level==1) cout<<root->key<<" ";
else if(level>1)
{
PrintLevel(root->LeftChild,level-1);
PrintLevel(root->RightChild,level-1);
}
}
void print(TreeNode *root,int levels)
{
if(!root) return;
for(int i=1;i<=levels;++i)
{
PrintLevel(root,i);
cout<<endl;
}
}
void FindPathCore(TreeNode *root,int key,vector<TreeNode *>& path,int& CurrentSum)
{
path.push_back(root);
CurrentSum+=root->key;
if(!root->LeftChild && !root->RightChild )
{
if(CurrentSum==key)
{
for(auto beg=path.begin();beg!=path.end();++beg)
cout<<(*beg)->key<<" ";
cout<<endl;
}
}
else
{
if(root->LeftChild)
FindPathCore(root->LeftChild,key,path,CurrentSum);
if(root->RightChild)
FindPathCore(root->RightChild,key,path,CurrentSum);
}
CurrentSum-=root->key;
path.pop_back();
}
void FindPath(TreeNode *root,int key)
{
if(!root)
return;
vector<TreeNode *> path;
int CurrentSum=0;
FindPathCore(root,key,path,CurrentSum);
}
int main()
{
TreeNode *root=nullptr;
int a[]={12,10,17,7,11,14,18,13,16};
int len=sizeof(a)/sizeof(a[0]);
for(int i=0;i<len;++i)
{
root=insert(root,a[i]);
}
print(root,4);
cout<<"==========="<<endl;
FindPath(root,33);
return 0;
}