-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbst-insertion.cpp
More file actions
127 lines (110 loc) · 2.25 KB
/
bst-insertion.cpp
File metadata and controls
127 lines (110 loc) · 2.25 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
#include<iostream>
using namespace std;
struct Node{
int info;
Node *left;
Node *right;
};
class binarytree{
public:
Node *temp,*temp1;
Node *root;
int number;
binarytree()
{
root=temp=temp1=NULL;
number=0;
}
void insert(Node *temp)
{
if(root==NULL){
temp=new Node;
temp->info=number;
temp->left=NULL;
temp->right=NULL;
root=temp;
return;
}
if(temp->info==number){
cout<<"Given number is alredy present in TREE"<<endl;
return;
}
if(temp->info < number){
if(temp->right!=NULL){
temp=temp->right;
insert(temp);
return;
}
else{
temp->right=new Node;
temp->right->info=number;
temp->right->left=NULL;
temp->right->right=NULL;
return;
}
}
if(temp->info > number){
if(temp->left!=NULL){
temp=temp->left;
insert(temp);
return;
}
else{
temp->left=new Node;
temp->left->info=number;
temp->left->left=NULL;
temp->left->right=NULL;
return;
}
}
}
void preorder(Node *temp)
{
if (temp==NULL)
{
cout<<"Empty BST detected";
return;
}
cout<<temp->info<<"-";
if (temp->left!=NULL)
preorder(temp->left);
if (temp->right!=NULL)
preorder(temp->right);
}
void postorder(Node *temp)
{
if (temp==NULL)
{
cout<<"Empty BST detected";
}
if (temp->left!=NULL)
{
postorder(temp->left);
}
if (temp->right!=NULL)
{
preorder(temp->right);
}
cout<<temp->info<<" ";
}
};
int main()
{
binarytree b;
b.number=10;
b.insert(b.root);
b.number=16;
b.insert(b.root);
b.number=15;
b.insert(b.root);
b.number=13;
b.insert(b.root);
b.number=5;
b.insert(b.root);
b.number=12;
b.insert(b.root);
//Traversal inorder,postorder,preorder
b.preorder(b.root);
cout<<endl;
b.postorder(b.root);
}