您的位置:首页 > 其它

二叉查找树之创建,遍历,删除

2012-09-26 21:31 274 查看
/* 二叉查找树 数据结构定义 */

typedef struct BSTreeNode

{

int data ;

struct BSTreeNode *lchild ;

struct BSTreeNode *rchild ;

}BSTreeNode ;

/* 插入 */

void InsertBST( BSTreeNode* &t, int key )

{

if( NULL == t )

{

t = ( BSTreeNode * )malloc( sizeof(BSTreeNode) ) ;

t->lchild = NULL ;

t->rchild = NULL ;

t->data = key ;

return ;

}

if( key < t->data )

InsertBST( t->lchild, key ) ;

else

InsertBST( t->rchild, key ) ;

}

/*中序遍历*/

void InOrderPrintf( BSTreeNode* node)

{

if(node != NULL)

{

InOrderPrintf(node->lchild);

printf(" %d ", node->data);

InOrderPrintf(node->rchild);

}

}

/*前序遍历*/

void PreOrderPrintf( BSTreeNode* node )

{

if( node != NULL )

{

printf( " %d ", node->data ) ;

PreOrderPrintf( node->lchild ) ;

PreOrderPrintf( node->rchild ) ;

}

}

/*后序遍历*/

void PostOrderPrintf( BSTreeNode* node )

{

if( node != NULL )

{

PostOrderPrintf( node->lchild ) ;

PostOrderPrintf( node->rchild ) ;

printf( " %d ", node->data ) ;

}

}

/*查找某个值key*/

BSTreeNode* BST_Search( BSTreeNode *t, int key )

{

if( t == NULL )

return NULL ;

else

{

if( key == t->data )

return t ;

else if( key < t->data )

return ( BST_Search( t->lchild, key ) ) ;

else

return ( BST_Search( t->rchild, key ) ) ;

}

}

/*删除某个节点key*/

void Delete_BST( BSTreeNode *t, int key )

{

BSTreeNode *p = t ;

BSTreeNode *f = NULL ;

BSTreeNode *q, *s ;

while( p!=NULL && p->data!=key )

{

f = p ;

if( p->data > key )

p = p->lchild ;

else

p = p->rchild ;

}

if( NULL == p )

return ;

s = p ;

if( p->lchild!=NULL && p->rchild!=NULL )

{

f = p ;

s = p->lchild ;

while( s->rchild != NULL )

{

f = s ;

s = s->rchild ;

}

p->data = s->data ;

}

if( s->lchild != NULL )

q = s->lchild ;

else

q = s->rchild ;

if( NULL == f )

t = q ;

else if( f->lchild == s )

f->lchild = q ;

else

f->rchild = q ;

free( s ) ;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐