1. 定义
你可以理解为折半查找以二叉树形式的表象。
lchild
|
data
|
rchild
|
parent
|
2. 操作
2.1 查找
BSTNode BSTSearch( BSTree tree, Data key )
{
if( !tree )
return NULL;
if( key == tree->data )
return tree;
else if ( key < tree->data )
BSTSearch( tree->lchild, key );
else
BSTSearch( tree->rchild, key );
}
2.2 插入
void BSTInsert( BSTree &*tree, Data key )
{
if( BSTSearch( tree, key ) )
return ;
node = new BSTNode(key);
if( tree == NULL )
tree = s;
BSTNode *x = tree, y=NULL;
while( x )
{
y = x;
if( key>x->data )
x = x->right;
else
x = x->left;
}
if( key < y->data)
y->left = s;
else
y->right = s;
s->right = s->left = NULL;
}
注:二叉搜索树可能会退化成链表,影响性能,所以才会有平衡树的出现。
2.3 删除
二叉搜索树的删除比较复杂,分为三种情况讨论:
(1)左右子树为空,直接删除。如图(a)
由于删去叶子结点不破坏整棵树的结构,则只需修改其双亲结点的指针即可。
(2)只有一个子树,如图(b)
(3)左右子树皆在,则让该节点与中序遍历的后一个节点交换,操作如图(c)。
void BSTDelete( BSTree &*p, Data key )
{
BSTNode *p = BSTSearch( p, key );
if( !p )
return ;
if( !p->rchild ) //右子树为空
{
q = p;
p = p->lchild;
free(q);
}
else if( !p->lchild ) //左子树为空
{
q= p;
p = p->rchild;
free(q);
}
else //右右子树不为空
{
q = p;
s = p->lchild;
while( s->rchild ) //查找中序遍历的后一个节点。
{
q = s;
s = s->rchild;
}
q->data = s->data;
free(s);
}
}