-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary_Search_Tree.cpp
135 lines (123 loc) · 2.3 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *newnode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data=data;
node->left=NULL;
node->right=NULL;
return node;
}
void inorder(struct node *root)
{
if(root!=NULL)
{
inorder(root->left);
printf("%d\n",root->data);
inorder(root->right);
}
}
struct node *insert(struct node *node,int data)
{
if(node==NULL)
{
return(newnode(data));
}
if(data<node->data)
{
node->left=insert(node->left,data);
}
else if(data>node->data)
{
node->right=insert(node->right,data);
}
return(node);
}
struct node* search(struct node *node,int data)
{
if (node->data == data)
{
printf("Data Found");
}
if(data<node->data)
{
return(search(node->left,data));
}
else if(data>node->data)
{
return(search(node->right,data));
}
}
struct node * minValueNode(struct node* node)
{
struct node* current = node;
while (current->left != NULL)
current = current->left;
return current;
}
struct node *deleteNode(struct node *root,int data)
{
if(root==NULL)
{
return root;
}
if(data<root->data)
{
root->left=deleteNode(root->left,data);
}
else if(data>root->data)
{
root->right=deleteNode(root->right,data);
}
else
{
if(root->left==NULL)
{
struct node *temp=root->right;
free(root);
return(temp);
}
if(root->right==NULL)
{
struct node *temp=root->left;
free(root);
return(temp);
}
struct node *temp=minValueNode(root->right);
root->data=temp->data;
root->right=deleteNode(root->right, temp->data);
}
return root;
}
int main()
{
struct node *root=NULL;
root=insert(root,50);
insert(root,30);
insert(root,20);
insert(root,40);
insert(root,70);
insert(root,60);
insert(root,80);
inorder(root);
printf("Inorder traversal of the given tree \n");
inorder(root);
printf("\nDelete 20\n");
root = deleteNode(root, 20);
printf("Inorder traversal of the modified tree \n");
inorder(root);
printf("\nDelete 30\n");
root = deleteNode(root, 30);
printf("Inorder traversal of the modified tree \n");
inorder(root);
printf("\nDelete 50\n");
root = deleteNode(root, 50);
printf("Inorder traversal of the modified tree \n");
inorder(root);
}