-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbst-mod.cpp
101 lines (93 loc) · 1.75 KB
/
bst-mod.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
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
//a tree for storing integers
class bnode {
private :
friend class int_tree;
bnode* left;
bnode* right;
int data;
int count;
bnode (int d, bnode* l, bnode* r):
data(d), left(l), right(r), count(1) {}
void print() const{
std::cout<<data<<" : "<<count<<" \t ";}
};
class int_tree {
public :
int_tree (){root = 0;}
void insert (int d);
int find (int d) const {
return (find (root,d));}
void print () const {
print (root);}
private :
bnode* root;
int find (bnode* r, int d) const;
void print (bnode* r) const;
};
void int_tree::insert (int d)
{
bnode* temp = root;
bnode* old;
if (root == 0){
root = new bnode (d,0,0);
return ;
}
while (temp != 0){
old = temp;
if (temp -> data == d){
(temp -> count)++;
return;
}
if (temp -> data > d)
temp = temp -> left;
else
temp = temp -> right;
}
if (old -> data > d)
old -> left = new bnode (d,0,0);
else
old -> right = new bnode (d,0,0);
}
int int_tree::find (bnode* r, int d) const
{
if (r == 0)
return 0;
else if (r -> data == d)
return (r -> data);
else if (r -> data > d)
return (find (r->left, d));
else
return (find (r->right, d));
}
void int_tree::print (bnode* r) const
{
if (r != 0){
print(r->left);
r->bnode::print();
print(r->right);
}
}
int main ( )
{
int_tree t;
int p;
while (std::cin>>p){
if (p==0)
break ;
t.insert(p);
}
t.print();
std::cout<<"\n Enter another zero to continue\n";
std::cin>>p;
int_tree itree;
for (int i=150; i>0 ; --i)
itree.insert(int(rand()));
itree.print();
std::cout<<"\nEnter another zero to terminate\n";
std::cin>>p;
return 0;
}