-
Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathdelete_nodes_BST.cpp
139 lines (130 loc) · 3.36 KB
/
delete_nodes_BST.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
#include <bits/stdc++.h>
using namespace std;
class Tree
{
public:
int val;
Tree *left;
Tree *right;
public:
//class constructor called when any object or pointer is created without any parameter.
Tree()
{
val=0;
left=nullptr;
right=nullptr;
}
//class constructor called when an object or pointer is called while passing an argument (val).
Tree(int val)
{
this->val=val;
this->left=nullptr;
this->right=nullptr;
}
//builds a Binary Tree taking (int) value as an argument and returns the root to the tree built.
Tree* buildTree(int val)
{
if(this==nullptr)
{
Tree *temp = new Tree(val);
return temp;
}
else
{
Tree *temp=nullptr;
if(this->val>val)
{
temp=this->left->buildTree(val);
this->left=temp;
}
else
{
temp=this->right->buildTree(val);
this->right=temp;
}
return this;
}
}
//RECURSIVE DFS PREORDER
void preOrder()
{
if(this!=nullptr)
{
cout<<this->val<<",";
this->left->preOrder();
this->right->preOrder();
}
}
};
Tree* deleteNode(Tree *root, int val)
{
if(root==nullptr)
return nullptr;
else
{
if(root->val>val)
root->left=deleteNode(root->left,val);
else if(root->val<val)
root->right=deleteNode(root->right,val);
else
{
if(root->left!=nullptr)
{
Tree *temp=root->left;
Tree *trav=temp->right;
if(trav==nullptr)
{
temp->right=root->right;
root=temp;
}
else
{
while(trav->right!=nullptr)
{
temp=trav;
trav=trav->right;
}
temp->right=trav->left;
root->val=trav->val;
trav->left=NULL;
}
}
else if(root->right!=nullptr)
{
Tree *temp=root->right;
Tree *trav=temp->left;
if(trav==nullptr)
{
temp->left=root->left;
root=temp;
}
else
{
while(trav->left!=nullptr)
{
temp=trav;
trav=trav->left;
}
temp->left=trav->right;
root->val=trav->val;
trav->right=NULL;
}
}
else
root=nullptr;
}
return root;
}
}
int main()
{
vector<int>test={8,5,3,6,11,10,9,12};
Tree *root=nullptr;
for(int i:test)
root=root->buildTree(i);
cout<<"The tree: ";
root->preOrder();
root=deleteNode(root,6);
cout<<"\nThe tree after deletion: ";
root->preOrder();
}