Im trying to insert into an array Based Binary Search tree.
I am not sure how i prevent overwriting data using left and right indexes...
Do i insert leftchild as tree[2 * i + 1] and rightchild as tree[2 * i + 2] ? I think it is for locating the position of a node given its name...
Thats my problem. Not knowing how to insert, recursively or iteratively(ive chosen recursively but it might be totally wrong).
BST::BST(int capacity) : items(new item[capacity]), size(0),
leftChild(0), rightChild(0), root_index(1)
{
items->empty = true;
maxSize = capacity-1;
}
Below is the insertion function. I have seen many that deal with Linked Lists implementations, But nothing array based! Here is my attempt:
void BST::insert(const data& aData)
{
if ( items[root_index].empty )
{
items[root_index].theData = aData;// Get the data.
items[root_index].empty = false;
oldRoot.theData = aData;
}
else
{
if ( aData < items[root_index].theData )
{
leftChild = root_index * 2;
if ( items[leftChild].empty )
{
items[leftChild].theData = aData;
items[leftChild].empty = false;
}//items->empty = true;
else
{
items[root_index].theData = items[leftChild].theData;
this->insert(aData);
}
}
else if ( items[root_index].theData < aData )
{
rightChild = root_index * 2 + 1;
if ( items[rightChild].empty )
{
items[rightChild].theData = aData;
items[rightChild].empty = false;
}
else//items->empty = true;
{
items[root_index].theData = items[rightChild].theData;
this->insert(aData);
}
}
else return;
}
items[1].theData = oldRoot.theData;
}
What is correct?...Does anyone have any array based suggstions for inserting? I appear to be stuck in an infinite recursion