-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathbinary_search_tree.cpp
119 lines (106 loc) · 2.2 KB
/
binary_search_tree.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
#include<iostream>
#include<queue>
#include<unordered_map>
using namespace std;
struct node{
int data;
node *left;
node *right;
node(int k)
{
data=k;
left=NULL;
right=NULL;
}
};
void BST_INSERT(node* root,int k) //iterative insertion in BST
{
node* temp = root;
while(temp!=NULL)
{
if(k<temp->data && temp->left == NULL)
{
temp->left = new node(k);
break;
}
else if(k< temp->data && temp->left != NULL)
temp = temp->left;
else if(k>temp->data && temp->right == NULL)
{
temp->right = new node(k);
break;
}
else if(k > temp->data && temp->right != NULL)
temp = temp->right;
else
break;
}
}
node* addnode()
{
int n,k;
node* root = NULL;
cout<<"enter the number of nodes";
cin>>n;
while(n--)
{
cin>>k;
if(root==NULL)
root = new node(k);
else
BST_INSERT(root,k);
}
return root;
}
void preorder(node *root)
{
if(root==NULL)
return;
cout<<root->data;
preorder(root->left);
preorder(root->right);
}
node* BST_DELETE(node* root,int k)
{
if(root == NULL)
return root;
if(k < root->data)
root->left = BST_DELETE(root->left,k);
else if(k > root->data)
root->right = BST_DELETE(root->right,k);
else
{
node*temp;
if(root->left == NULL)
{
struct node *temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
struct node *temp = root->left;
free(root);
return temp;
}
temp = root->right;
while(temp!=NULL) //find inorder successor
{
if(temp->left == NULL)
break;
temp = temp->left;
}
root->data = temp->data;
root->right = BST_DELETE(root->right,temp->data);
}
return root;
}
int main()
{
node * root = addnode();
preorder(root);
BST_DELETE(root,4);
cout<<"\n";
preorder(root);
return 0;
}