Repository navigation
Expand file tree
/
Copy pathBST_delete.cpp
More file actions
140 lines (121 loc) · 2.91 KB
/
Copy pathBST_delete.cpp
File metadata and controls
140 lines (121 loc) · 2.91 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#include <bits/stdc++.h>
using namespace std;
struct Node {
int value;
Node* left;
Node* right;
};
Node* newNode(int value) {
Node* node = new Node;
node->value = value;
node->left = node->right = nullptr;
return node;
}
Node* insert(Node* root, int value) {
if (root == nullptr) {
return newNode(value);
}
if (value < root->value) {
root->left = insert(root->left, value);
}
else if (value > root->value) {
root->right = insert(root->right, value);
}
return root;
}
Node* KthLargest(Node* root, int k,int* count)
{
if (root == nullptr)
{
return nullptr;
}
Node* element = KthLargest(root->right,k,count);
if (element)
{
return element;
}
(*count)++;
if (*count == k)
{
return root;
}
return KthLargest(root->left,k,count);
}
Node* findElementToDel(Node* root, int k)
{
int count = 0;
return KthLargest(root, k,&count);
}
Node* findNodeToReplace(Node* root) {
Node* current = root;
while (current && current->left) {
current = current->left;
}
return current;
}
Node* deleteElement(Node* root, int kValue) {
if (root == nullptr) {
return root;
}
if (kValue < root->value) {
root->left = deleteElement(root->left, kValue);
}
else if (kValue > root->value) {
root->right = deleteElement(root->right, kValue);
}
else {
if (root->left == nullptr && root->right == nullptr) {
delete root;
root = nullptr;
return root;
}
if (root->left == nullptr) {
Node* node = root->right;
delete root;
root = node;
return root;
}
if (root->right == nullptr) {
Node* node = root->left;
delete root;
root = node;
return root;
}
Node* node = findNodeToReplace(root->right);
root->value = node->value;
root->right = deleteElement(root->right, root->value);
}
return root;
}
void print(Node* root) {
if (root == nullptr) {
return;
}
queue<Node*> toPrint;
toPrint.push(root);
while (!toPrint.empty()) {
Node* node = toPrint.front();
toPrint.pop();
cout << node->value << " ";
if (node->left) {
toPrint.push(node->left);
}
if (node->right) {
toPrint.push(node->right);
}
}
}
int main() {
int n, k;
cin >> n >> k;
Node* root = nullptr;
for (int i = 0; i < n; i++) {
int node;
cin >> node;
root = insert(root, node);
}
Node* nodeToDel = findElementToDel(root, k);
deleteElement(root, nodeToDel->value);
print(root);
return 0;
}