-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBST_delete_node.cpp
142 lines (110 loc) · 2.13 KB
/
BST_delete_node.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
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
struct Node* createNode(int data)
{
struct Node * newnode;
newnode = (struct Node *) malloc(sizeof(struct Node));
newnode->data = data;
newnode->left = 0;
newnode->right = 0;
return newnode;
}
struct Node* insert(struct Node* node, int data)
{
if (node == 0)
{
return createNode(data);
}
else if (data < node->data)
{
node->left = insert(node->left, data);
}
else
{
node->right = insert(node->right, data);
}
return node;
}
struct Node* searchBST(struct Node* root, int data)
{
if (root == 0)
return 0;
if (data == root->data)
return root;
else if (data < root->data)
return searchBST(root->left, data);
else
return searchBST(root->right, data);
}
struct Node* inordersecc(struct Node* root)
{
struct Node * temp = root;
while (temp&&temp->left!=NULL)
{
temp = temp->left;
}
return temp;
}
struct Node* deleteBST(struct Node* root, int data)
{
if (root == NULL)
return root;
if (data < root->data)
root->left = deleteBST(root->left, data);
else if (data > root->data)
root->right = deleteBST(root->right, data);
else
{ if (root->left == NULL && root->right == NULL)
return NULL;
else if (root->left == NULL)
{
root = root->right;
return root;
}
else if (root->right == NULL)
{
root = root->left;
return root;
}
struct Node* temp = inordersecc(root->right);
root->data = temp->data;
root->right = deleteBST(root->right, temp->data);
}
return root;
}
void inorder(struct Node * root)
{
if (root != NULL) {
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
}
int main()
{
struct Node* root = 0;
root = insert(root, 5);
root = insert(root, 10);
root = insert(root, 4);
root = insert(root, 2);
root = insert(root, 3);
root = insert(root, 12);
root = insert(root, 8);
inorder(root);
cout << endl;
if (searchBST(root, 1) == NULL)
cout << "data is not exist" << endl;
else
cout << "data is exist " << endl;
root = deleteBST(root, 10);
inorder(root);
root = deleteBST(root, 10);
cout<<endl;
inorder(root);
}