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
|
CDNode<KEY, VALUE>* maintain(CDNode<KEY, VALUE>* subtree) {
subtree->decrease_timer();
if (subtree->timer() > 0) {
return subtree;
}
else {
int k = 0;
k = tree_size(subtree);
CDNode<KEY, VALUE> **array;
array = new CDNode<KEY, VALUE>*[k];
for (int i = 0; i < k; i++) {
array[tree_to_array(array, 0, subtree)] = NULL;
}
subtree = array_to_tree(array, 0, k);
for (int j = 0; j < k; j++) {
delete array[j];
}
delete[] array;
return subtree;
}
}
int tree_size(CDNode<KEY, VALUE>* subtree) {
if (NULL == subtree)
{
return 0;
}
else
return tree_size(subtree->left()) + 1 + tree_size(subtree->right());
}
int tree_to_array(CDNode<KEY, VALUE> **array_of_pointers, int start_index, CDNode<KEY, VALUE>* subtree) {
if (NULL == subtree) {
return start_index;
}
else {
start_index = tree_to_array(array_of_pointers, start_index, subtree->left());
array_of_pointers[start_index] = subtree;
}
return tree_to_array(array_of_pointers, start_index + 1, subtree->right());
}
CDNode<KEY, VALUE>* array_to_tree(CDNode<KEY, VALUE> **array_of_pointers, int start_index, int end_index) {
int NUM_OF_NODES = (end_index - start_index);
if (NUM_OF_NODES == 0) {
return NULL;
}
else {
int middle = (start_index + end_index) / 2;
_root = array_of_pointers[middle];
_root->set_left(array_to_tree(array_of_pointers, start_index, middle));
_root->set_right(array_to_tree(array_of_pointers, middle + 1, end_index));
if (NUM_OF_NODES >= 3) {
int result = 0;
result = 1 + ((NUM_OF_NODES - 1) / 3);
_root->set_timer(result);
}
else {
_root->set_timer(1);
}
}
return _root;
}
|