-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search_tree_deletion.cpp
More file actions
118 lines (106 loc) · 1.85 KB
/
binary_search_tree_deletion.cpp
File metadata and controls
118 lines (106 loc) · 1.85 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
#include<iostream>
using namespace std;
struct Node
{
int key;
Node *left, *right;
};
Node* newnode(int key)
{
//inserting newnode at leaf
Node* temp=new Node();
temp->key=key;
temp->left=temp->right=NULL;
return temp;
}
Node* insert(Node* root, int key)
{
//if node is null
if(root==NULL)
return newnode(key);
if(key<root->key)
{
root->left=insert(root->left,key);
}
if(key>root->key)
{
root->right=insert(root->right,key);
}
return root;
}
Node* minValueNode(Node* root)
{
Node* cur=root;
while(cur!=NULL && cur->left!=NULL)
{
cur=cur->left;
}
return cur;
}
Node* deleteNode(Node* node,int key)
{
//if node is null then return this node
if(node==NULL)
return node;
//if
if(key<node->key)
{
node->left=deleteNode(node->left,key);
}
else if(key>node->key)
{
node->right=deleteNode(node->right,key);
}
else
{
//if key is equal to value at node and has one child or no
if(node->left==NULL)
{
Node* temp=node->right;
free(node);
return temp;
}
else if(node->right==NULL)
{
Node* temp=node->left;
free(node);
return temp;
}
//if node has both children then replace it with next inorder value
Node* temp=minValueNode(node->right);
//replace it with inorder successor
node->key=temp->key;
//delete the inorder successor
node->right=deleteNode(node->right,temp->key);
}
}
void inorder(Node* root)
{
if(root!=NULL)
{
inorder(root->left);
cout<<root->key<<"\t";
inorder(root->right);
}
}
int main()
{
Node* root=NULL;
root=insert(root,20);
insert(root,10);
insert(root,30);
insert(root,50);
insert(root,40);
insert(root,10);
insert(root,30);
//printing the contents of binary tree
cout<<"Contents -\n";
inorder(root);
cout<<endl;
//delete the node with key 20
root=deleteNode(root,20);
cout<<"Contents of modified tree -\n";
inorder(root);
cout<<endl;
return 0;
}