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

来源:互联网 发布:自学小提琴的软件 编辑:程序博客网 时间:2024/05/29 08:39

/* 二叉查找树 数据结构定义 */
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 ) ;

}

原创粉丝点击