-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbst1.cpp
More file actions
117 lines (96 loc) · 1.72 KB
/
bst1.cpp
File metadata and controls
117 lines (96 loc) · 1.72 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
#include<iostream>
using namespace std;
struct node{
int data;
node *left;
node *right;
};
node *root= NULL;
node* get_node(int data){
node *temp= new node();
temp->data= data;
temp->left= NULL;
temp->right= NULL;
return temp;
}
// BST class
class binaryst{
public:
// Inserting a element in a node;
node* insert(int data,node* root){
if(root == NULL){
root= get_node(data);
}
else if(data<= root->data){
root= insert(data,root->left);
}
else {
root= insert(data,root->right);
}
return root;
}
// Searching in a binary tree
bool search(node *root, int data){
if(root== NULL){
return false;
}
else if(data== root->data){
return true;
}
else if(data < root->data){
search(root->left,data);
}
else {
search(root->right,data);
}
}
// preorder Traversal
void preorder(node *root){
if(root == NULL){
return ;
}
else{
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
}
// Inorder traversal
void Inorder(node *root){
if(root == NULL){
return ;
}
else{
Inorder(root->left);
cout<<root->data<<" ";
Inorder(root->right);
}
}
// Postorder traversal
void Postorder(node *root){
if(root == NULL){
return ;
}
else{
Postorder(root->left);
Postorder(root->right);
cout<<root->data<<" ";
}
}
};
int main(){
cout<<"Binary Search Tree";
binaryst b;
for(int i=23;i<33;i++){
root= b.insert(i,root);}
int n;
cin >>n;
b.search(root,n);
cout<<"Preorder";
b.preorder(root);
cout<<"Postorder";
b.Postorder(root);
cout<<"Inorder";
b.Inorder(root);
return 0;
}