-
Notifications
You must be signed in to change notification settings - Fork 0
/
AVL_Tree_Deletion.cpp
63 lines (53 loc) · 1.27 KB
/
AVL_Tree_Deletion.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
int Inordertraversal(Node* root, vector<int>& result)
{
if (root == nullptr)
{
return 0;
}
Inordertraversal(root->left, result);
result.push_back(root->data);
Inordertraversal(root->right, result);
return 0;
}
Node* newNode(int data)
{
Node* node = new Node(data);
node->data = data;
node->left = nullptr;
node->right = nullptr;
return node;
}
Node* constructBSTFromSortedArray(vector<int>& result, int start, int end)
{
if (start > end)
{
return nullptr;
}
int mid = (start + end) / 2;
Node* root = newNode(result[mid]);
root->left = constructBSTFromSortedArray(result, start, mid - 1);
root->right = constructBSTFromSortedArray(result, mid + 1, end);
return root;
}
Node* deleteNode(Node* root, int data)
{
vector<int> result;
Inordertraversal(root, result);
int size = result.size();
int indexToDelete = -1;
for (int i = 0; i < size; i++)
{
if (result[i] == data)
{
indexToDelete = i;
break;
}
}
if (indexToDelete == -1)
{
return root;
}
result.erase(result.begin() + indexToDelete);
Node* newRoot = constructBSTFromSortedArray(result, 0, result.size() - 1);
return newRoot;
}