BSTについてもう少し助けが必要です。これは、挿入したときの私のBSTの外観です。
R、L、J、G
R --Root at Index 0
/ \
L @ Index1 L NULL
/ \
J @ Index3 J NULL
/ \
G @ Index7 G NULL
これを実現するコードは次のとおりです。
void BST::insert(const data &aData)
{
if ( items[Parent].empty )
{
items[Parent].theData = aData; // insert at leaf.
items[Parent].empty = false;
size++;
return;
}
for ( int i = 0; i <= size; i++ )
{
if ( aData < items[Parent].theData )
{
if ( items[2*i+1].empty )
{
items[2*i+1].theData = aData;
items[2*i+1].empty = false;
}
else
{
// we must already have a left child to some root.
Parent++; So make the previous data the root???
if ( items[Parent].empty )
{
items[Parent].theData = items[2*i+1].theData;
items[Parent].empty = false;
Parent = (i-1)/2;
}
}
}
else
{ ...// do the same for data greater than but with items[2*i+2] }
私の質問は、いつ新しいルートを作成する必要があるのかということです。いつ新しいルートを作成する必要がありますか?再比較のために?
このアプローチは正しいですか?私の投稿を見てくれた両方の人に感謝します:)
//コンストラクターBSTクラスとそのプライベートセクション。
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