-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTree.cc
127 lines (117 loc) · 2.37 KB
/
Tree.cc
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
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <iostream>
#include <algorithm>
#include <stdlib.h>
#include <time.h>
#include <vector>
using namespace std;
struct Node{
int v;
Node* l;
Node* r;
Node(){
l = NULL;
r = NULL;
}
Node(int v_){
v = v_;
Node();
}
};
class Tree{
public:
Node* root;
Tree(){
root = NULL;
}
void insert(int v){
if(not root){
root = new Node(v);
return;
}
insert(root, v);
}
void insert(Node* node, int v){
if(node->v > v){
if(not node->l){
node->l = new Node(v);
return;
}else{
insert(node->l, v);
}
}else{
if(not node->r){
node->r = new Node(v);
return;
}else{
insert(node->r, v);
}
}
}
void traverse(int i=0){
if(i == 0){
recursion(root);
cout<<endl;
}else{
iterate();
cout<<endl;
}
}
void iterate(){
vector<Node*> l;
auto node = root;
while(node){
l.push_back(node);
node = node->l;
}
while(not l.empty()){
auto node = l.back();
l.pop_back();
cout<<node->v<<" ";
if(node->r){
l.push_back(node->r);
node = node->r->l;
while(node){
l.push_back(node);
node = node->l;
}
}
}
}
void recursion(Node* node){
if(not node) return;
if(not node->l){
cout<<node->v<<" ";
recursion(node->r);
}else{
recursion(node->l);
cout<<node->v<<" ";
recursion(node->r);
}
}
};
int main(int argc, char* argv[]){
int len = 20;
if(argc>1) len = atoi(argv[1]);
srand(time(NULL));
vector<int> l(len);
for(int i=0;i<len;i++) l[i] = i+1;
for(int i=0;i<len;i++){
int j = rand()%len;
swap(l[i],l[j]);
}
/**
for(auto i:l){
cout<<i<<" ";
}
cout<<endl;
sort(l.begin(), l.end());
for(auto i:l){
cout<<i<<" ";
}
cout<<endl;
**/
Tree tree;
for(int i:l) tree.insert(i);
tree.traverse(1);
return 0;
}