CodePudding user response:
#includeusing namespace std;
Template
{
BTreeNode ()
: _pParent (NULL)
_size (0)
{
For (size_t I=0; I & lt;=M; I++)
{
_pSub [I]=NULL;
}
}
K _key [M];
BTreeNode
BTreeNode
Size_t _size;
};
Template
{
Typedef BTreeNode
Typedef Node * pNode;
Public:
BTree ()
: _pRoot (NULL)
{}
Bool Insert (K& Key)
{
If (_pRoot==NULL)//no root node
{
_pRoot=new Node ();
_pRoot - & gt; _key [0]=key;
_pRoot - & gt; _size=1;
return true;
}
Pair
If (ret. Second & gt;=0)
return false;
PNode pCur=ret. First;
PNode pSub=NULL;
While (1)
{
_Insert (pCur, key, pSub);
Size_t size=pCur - & gt; _size;
If (size & lt; M)
return true;
The else
{
Size_t mid=size & gt;> 1;
PNode TMP=new Node ();
For (size_t I=mid + 1; I & lt; The size; I++)
{
TMP - & gt; _key/TMP - & gt; _size=pCur - & gt; _key [I];
TMP - & gt; _pSub/TMP - & gt; _size=pCur - & gt; _pSub [I];
If (TMP - & gt; _pSub [TMP - & gt; _size])
TMP - & gt; _pSub [TMP - & gt; _size] - & gt; _pParent=TMP;
TMP - & gt; _size + +;
}
TMP - & gt; _pSub/TMP - & gt; _size=pCur - & gt; _pSub [pCur - & gt; _size];
If (TMP - & gt; _pSub [TMP - & gt; _size])
TMP - & gt; _pSub [TMP - & gt; _size] - & gt; _pParent=TMP;
PCur - & gt; _size -=(TMP - & gt; _size + 1);//processing size
If (pCur==_pRoot)//if the current node is the root node, also need to deal with the
{
_pRoot=new Node;
_pRoot - & gt; _key [0]=pCur - & gt; _key (mid),
_pRoot - & gt; _pSub [0]=pCur;
PCur - & gt; _pParent=_pRoot;
_pRoot - & gt; _pSub [1]=TMP;
TMP - & gt; _pParent=_pRoot;
_pRoot - & gt; _size=1;
return true;
}
The else
{
Key=pCur - & gt; _key (mid),
PCur=pCur - & gt; _pParent;
PSub=TMP;
}
}
}
}
Pair
{
PNode pCur=_pRoot;
PNode pParent=NULL;
While (pCur)
{
Size_t I=0;
While (I & lt; PCur - & gt; _size)
{
If (key==pCur - & gt; _key [I])
Return pair
Else if (key & lt; PCur - & gt; _key [I])
break;
The else
i++;
}
PParent=pCur;
PCur=pCur - & gt; _pSub [I];
}
Return make_pair (pParent, 1);//there is no return - 1
}
Private:
Void _Insert (pNode pCur, const K& The key, pNode pSub)
{
The thought of//direct insert
Int the end=pCur - & gt; _size - 1;
While (key & lt; PCur - & gt; _key [end] & amp; & End & gt;=0)
{
PCur - & gt; _key [end + 1]=pCur - & gt; _key [end];
PCur - & gt; _pSub [end + 2]=pCur - & gt; _pSub [end + 1];
End -;
}
PCur - & gt; _key [end + 1]=key;
PCur - & gt; _pSub [end + 2]=pSub;
If (pSub)
PSub - & gt; _pParent=pCur;
PCur - & gt; _size +=1;
}
Private:
Node * _pRoot;
};
Int main ()
{
Int arr []={53, 75, 139, 49, 145, 36, 101};
BTree
Size_t size=sizeof (arr)/sizeof (arr [0]).
For (size_t I=0; I & lt; 7. I++)
B.I nsert (arr [I]);
system("pause");
return 0;
}