/************************************************************
二叉排序树的查找与删除
Designed BY LU 2014.12.12
************************************************************/
#include<iostream>
#include<malloc.h>
using namespace std;
#define TRUE 1
#define FALSE 0
#define EQ(a,b) ((a)==(b))
#define LT(a,b) ((a)<(b))
#define LQ(a,b) ((a)<=(b))
#define N 10
typedef int KeyType;
struct ElemType
{
KeyType key;
int others;
};
typedef ElemType TElemType;
typedef int Status;
typedef struct BiTNode
{
TElemType data;
BiTNode *lchild,*rchild; // 左右孩子指针
} BiTNode,*BiTree;
void InitBiTree(BiTree &T)
{
T=NULL;
}
Status SearchBST(BiTree T, KeyType key, BiTree f, BiTree &p)
{
if(!T)
{
p = f;
return FALSE;
}
else if EQ(key, T->data.key)
{
p = T;
return TRUE;
}
else if LT(key, T->data.key)
return SearchBST(T->lchild, key, T, p);
else
return SearchBST(T->rchild, key, T, p);
}
Status InsertBST(BiTree &T, ElemType e)
{
BiTree p,s;
if(!SearchBST(T, e.key, NULL, p))
{
s = (BiTree)malloc(sizeof(BiTree));
s->data = e;
s->lchild = s->rchild = NULL;
if(!p)
T = s;
else if LT(e.key, p->data.key)
p->lchild = s;
else
p->rchild = s;
return TRUE;
}
else return FALSE;
}
Status Delete(BiTree &p)
{
BiTree q, s;
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;
}
p->data = s->data;
if(q != p)
q->rchild = s->lchild;
else
q->lchild = s->lchild;
delete s;
}
return TRUE;
}
Status DeleteBST(BiTree &T, KeyType key)
{
if(!T)
return FALSE ;
else
{
if(EQ(key, T->data.key))
return Delete(T);
else if(LT(key, T->data.key))
return DeleteBST(T->lchild, key);
else
return DeleteBST(T->rchild, key);
}
}
void InOrderTraverse(BiTree T,void(*Visit)(TElemType))
{
if(T)
{
InOrderTraverse(T->lchild,Visit);
Visit(T->data);
InOrderTraverse(T->rchild,Visit);
}
}
void print(ElemType c)
{
cout<<"("<<c.key<<","<<c.others<<") ";
}
int main()
{
BiTree dt=NULL,f,t;
int i,p;
KeyType j;
ElemType r[N] = {{45,1},{12,2},{53,3},{3,4},{37,5},{24,6},{100,7},{61,8},{90,9},{78,10}};
InitBiTree(dt);
for(i = 0; i<N; i++)
InsertBST(dt,r[i]);
InOrderTraverse(dt,print);
cout<<endl;
cout<<"请输入待查找的值: "<<endl;
cin>>j;
p = SearchBST(dt, j,NULL,f);
if(p)
{
cout<<"表中存在此值."<<endl;
DeleteBST(dt,j);
cout<<"删除此值后: "<<endl;
InOrderTraverse(dt,print);
cout<<endl;
}
}
1
、设计一个读入一串整数构成一棵二叉排序树的算法。
2、试从二叉排序树中删除一个结点,是该二叉树仍为二叉排序树。