中序遍历
void NiceInOrder(BSTree &myt)
{
for(BstNode *p = First(myt.root) ; p != NULL ; p = Next(p))
{
cout<<p->data<<" ";
}
cout<<endl;
}
逆置中序遍历
void ResNiceInOrder(BSTree &myt)
{
for(BstNode *p = Last(myt.root) ; p != NULL ; p = Prev(p))
{
cout<<p->data<<" ";
}
cout<<endl;
}
删除
bool Remove_Value(BSTree &myt , ElemType val)
{
if(myt.root == NULL) return false;
BstNode *p = FindValue(myt , val);
if(p == NULL) return false;
if(p->leftchild != NULL && p->rightchild != NULL)
{
BstNode *tmp = Next(p->rightchild);
p->data = tmp->data;
p = tmp;
}
//leaf
BstNode *pa = p->parent;
BstNode *child = p->leftchild != NULL? p->leftchild:p->rightchild;
if(child != NULL) child->parent = pa;
if(pa != NULL)
{
myt.root = p;
}
else
{
if(pa->leftchild == p)
{
pa->leftchild = child;
}
else
{
pa->rightchild = child;
}
Freenode(p);
myt.cursize -=1;
return true;
}
}
插入
bool Inster_BSTree(BSTree &myt , ElemType val)
{
BstNode *p = myt.root;
BstNode *pa = NULL;
while(p != NULL && p->data != NULL)
{
pa = p;
p = val < p->data? p->leftchild:p->rightchild;
}
if(p != NULL && p->data == val) return false;
//
p = Buynode();
p->data = val;
p->parent = pa;
if(pa == NULL)
{
myt.root = p;
}
else
{
if(pa->data > p->data)
{
pa->leftchild = pa;
}
else
{
pa->rightchild = p;
}
myt.cursize += 1;
return true;
}
}
找最小值(中序遍历第一个值)
BtNode *First(BtNode *ptr)
{
while(ptr != NULL && ptr->leftchild != NULL)
{
ptr = ptr->leftchild;
}
return ptr;
}
找最大值(中序遍历最后一个值)
BtNode *Last(BtNode *ptr)
{
while(ptr != NULL && ptr->rightchild != NULL)
{
ptr = ptr->rightchild;
}
return ptr;
}
找前驱
BstNode *Prev(BtNode *ptr)
{
if(ptr == NULL) return NULL;
if(ptr->leftchild != NULL)
{
return Last(ptr->leftchild);
}
else
{
BstNode *pa = ptr->parent;
while(pa != NULL && pa->rightchild != ptr)
{
ptr = pa;
pa = pa->parent;
}
return pa;
}
}
找后继
BstNode *Next(BtNode *ptr)
{
if(ptr == NULL) return NULL;
if(ptr->rightchild != NULL)
{
return First(ptr->rightchild);
}
else
{
BstNode *pa = ptr->parent;
while(pa != NULL && pa->leftchild != ptr)
{
ptr = pa;
pa = pa->parent;
}
return pa;
}
}