Ho cercato di farlo recursively..The varaible intero genitore è come i, conforme alla formula, 2*i +1per la leftChild's e 2*i +2per il diritto.
void BST::insert(const data &aData)
{
if ( items[Parent].empty )
{
items[Parent].theData = aData;
items[Parent].empty = false;
}
else if ( aData < items[Parent].theData )
{
Parent = 2 * Parent + 1;
if ( Parent >= maxSize ) this->reallocate();
this->insert(aData);
}
else
{
Parent = (2 * rightChild++)+ 2;
if ( Parent >= maxSize ) this->reallocate();
this->insert(aData);
}
}
Funziona bene quando si inseriscono elementi che sono meno del genitore originale ... Ma quando trovo qualcosa che è più grande che tutte le viti su: x
void BST::reallocate()
{
item *new_array = new item[maxSize*2];
for ( int array_index = 0; array_index < maxSize; array_index++ )
{
if ( ! items[array_index].empty )
{
new_array[array_index].theData = items[array_index].theData;
}
}
maxSize *= 2;
delete [] items;
items = NULL;
items = new_array;
}
Qui è la mia ctor così nessuno si faccia più confusa è allora che sono:
BST::BST(int capacity) : items(new item[capacity]), size(0), Parent(0),
leftChild(0), rightChild(0)
{
items->empty = true;
maxSize = capacity;
}
private:
int size; // size of the ever growing/expanding tree :)
int Parent;
int maxSize;
int leftChild;
int rightChild;
struct item
{
bool empty;
data theData;
};
item *items; // The tree array
La funzione di inserimento di cui sopra è in realtà il meglio che posso ottenere ..
R
/ \
/ \
/ \
L X
/ \ / \
J V K T <--The only out of place node.
/ \ \
/ NULL \
G /
P
Quando si inseriscono: R, L, J, G, X, K, V, P, Tin questo ordine













