-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbtreeClass.cpp
More file actions
136 lines (119 loc) · 2.24 KB
/
btreeClass.cpp
File metadata and controls
136 lines (119 loc) · 2.24 KB
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
128
129
130
131
132
133
134
135
136
#include <iostream>
#include <iomanip>
using namespace std;
class tree{
public:
struct Node{
int key_value;
Node *left;
Node *right;
};
tree(){
root==NULL;
}
~tree(){
//destroy_tree();
}
void insert(int key){
if(root!=NULL){
insert(key, root);
}else{
root=new Node();
root->key_value=key;
root->left=NULL;
root->right=NULL;
}
}
Node *search(int key){
return search(key, root);
}
void destroy_tree(){
destroy_tree(root);
}
void display(){
display(root);
}
private:
Node *root;
// void display(Node *leaf, int indent =0){
// if(leaf!=NULL){
// cout<<leaf->key_value<<endl;
// cout <<setw(indent) << ' '<<"\\\n";
// display(leaf->left, indent+4);
// display(leaf->right, indent+4);
// }
// }
void display(Node *leaf, int indent=0){
if(leaf!=NULL){
if(leaf->right){
display(leaf->right, indent+4);
}
if(indent){
cout<<setw(indent)<<' ';
}
if(leaf->right)
cout<<" /\n"<<setw(indent)<<' ';
cout<<leaf->key_value<< "\n";
if(leaf->left){
cout<<setw(indent)<<' '<<" \\\n";
display(leaf->left, indent+4);
}
}
}
void destroy_tree(Node *leaf){
if(leaf!=NULL){
destroy_tree(leaf->left);
destroy_tree(leaf->right);
delete leaf;
}
}
void insert(int key, Node *leaf){
if(key< leaf->key_value){
if(leaf->left!=NULL){
insert(key, leaf->left);
}else{
leaf->left = new Node();
leaf->left->key_value = key;
leaf->left->left=NULL;
leaf->left->right=NULL;
}
}
else if(key>=leaf->key_value){
if(leaf->right!=NULL){
insert(key, leaf->right);
}else{
leaf ->right = new Node();
leaf->right->key_value = key;
leaf->right->left=NULL;
leaf->right->right=NULL;
}
}
}
Node *search(int key, Node *leaf){
if(leaf!=NULL){
if(key==leaf->key_value)
return leaf;
if(key<leaf->key_value)
return search(key, leaf->left);
else
return search(key, leaf->right);
}
else return NULL;
}
};
//http://www.cprogramming.com/tutorial/lesson18.html
int main(){
tree a;
a.insert(2);
a.insert(1);
a.insert(3);
a.insert(7);
a.insert(10);
a.insert(2);
a.insert(5);
a.insert(8);
a.insert(6);
a.insert(4);
a.display();
return 0;
}