delete.c
2.57 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
/**
* \file
*
* \author Georg Hopp
*
* \copyright
* Copyright © 2014 Georg Hopp
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "trbase.h"
#include "tr/tree.h"
void *
TR_treeDelete(TR_Tree this, const void * search, TR_TreeComp comp)
{
TR_TreeNode node;
TR_TreeNode del_node;
TR_TreeNode sibling;
int found;
void * data;
node = this->root;
TR_TREE_FIND(node, search, found, comp);
/*
* nothing was found...return NULL to indicate this.
*/
if (found != 0) {
return NULL;
}
/*
* we found an element, store its data pointer as we are
* up to delete it.
*/
data = node->data;
/*
* now remove the element.
*/
/*
* if we have two children replace data with the one from
* out inOrderSuccessor and remove the inOrderSuccessor.
*/
if (NULL != TR_TREE_LEFT(node) && NULL != TR_TREE_RIGHT(node)) {
TR_TreeNode successor;
TR_TREE_INORDER_SUCC(node, successor);
node->data = successor->data;
node = successor;
}
{
TR_TreeNode child = TR_TREE_CHILD(node);
/*
* if we still have one child replace ourself with it.
*/
TR_TREE_REPLACE_NODE(&(this->root), node, child);
/*
* and finally delete the node...and prepare ourselfs
* for rebalancing.
*/
if (rbBlack == node->color) {
if (NULL != child && rbRed == child->color) {
child->color = rbBlack;
TR_delete(node);
return data;
} else {
del_node = node;
if (NULL != child) {
node = child;
} else {
node->color = rbBlack;
node->left = NULL;
node->right = NULL;
}
}
} else {
TR_delete(node);
return data;
}
}
/*
* now comes rebalancing...note that if we came to this point
* the node is still not deleted.
* This is because I am not sure if it is needed during the
* rebalancing process...(this does not make much sense, but
* to be honest I don't know now.)
*/
TR_TREE_BALANCE_DELETE(&(this->root), node, sibling);
TR_delete(del_node);
return data;
}
// vim: set ts=4 sw=4: