-
Notifications
You must be signed in to change notification settings - Fork 56
/
BST.cpp
147 lines (139 loc) · 3.56 KB
/
BST.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#include<iostream>
using namespace std;
struct Node
{
int data;
Node *lchild;
Node *rchild;
Node(int value)
{
data=value;
lchild=NULL;
rchild=NULL;
}
};
class BST{
Node *root;
public:
BST()
{
root=NULL;
}
Node *getRoot()
{
return root;
}
void insert(int);
void inorderTraversal(Node *);
void preorderTraversal(Node *);
void postorderTraversal(Node *);
bool search(int);
int findLargestElement(Node *);
};
void BST::insert(int val)
{
Node *ptr=new Node(val);
if(root==NULL)
root=ptr;
else{
Node *curr=root;
Node *parent=NULL;
while(curr!=NULL)
{
parent=curr;
if(val<curr->data)
curr=curr->lchild;
else
curr=curr->rchild;
}
if(val<parent->data)
parent->lchild=ptr;
else
parent->rchild=ptr;
}
return;
}
void BST::inorderTraversal(Node *tree)
{
if(tree!=NULL)
{
inorderTraversal(tree->lchild);
cout<<tree->data<<endl;
inorderTraversal(tree->rchild);
}
}
void BST::preorderTraversal(Node *tree)
{
if(tree!=NULL)
{
cout<<tree->data<<endl;
preorderTraversal(tree->lchild);
preorderTraversal(tree->rchild);
}
}
void BST::postorderTraversal(Node *tree)
{
if(tree!=NULL)
{
postorderTraversal(tree->lchild);
postorderTraversal(tree->rchild);
cout<<tree->data<<endl;
}
}
bool BST::search(int key)
{
if(root==NULL) return false;
Node *curr=root;
while(curr!=NULL)
{
if(key<curr->data) curr=curr->lchild;
else if(key>curr->data) curr=curr->rchild;
else return true;
}
return false;
}
int main()
{
BST MyTree;
int choice,value,key;
do{
cout<<"1. Insert any value: "<<endl;
cout<<"2. for inordertraversal for the tree:"<<endl;
cout<<"3. for preordertraversal for the tree"<<endl;
cout<<"4. for postordertraversal of the tree"<<endl;
cout<<"5. search any element in the tree"<<endl;
cout<<"Enter your choice:"<<endl;
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter value to insert";
cin>>value;
MyTree.insert(value);
break;
case 2:
MyTree.inorderTraversal(MyTree.getRoot());
break;
case 3:
MyTree.preorderTraversal(MyTree.getRoot());
break;
case 4:
MyTree.postorderTraversal(MyTree.getRoot());
break;
case 5:
cout << "Enter value to search: ";
cin >> key;
if (MyTree.search(key))
cout << "Element found in the tree." << endl;
else
cout << "Element not found in the tree." << endl;
break;
case 0:
cout<<"exit......."<<endl;
break;
default:
cout<<"Invalid choice"<<endl;
}
}while(choice!=0);
return 0;
}