动态查找

#include <iostream.h>
#include <malloc.h>
typedef int ElemType;
typedef struct BiTNode
{
ElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
bool SearchBST(BiTree T,ElemType key,BiTree f,BiTree &p)
{
if(!T) {p=f;return false;}
else if(T->data==key) {p=T;return true;}
else if(T->data >key) return SearchBST(T->lchild,key,T,p);
else return SearchBST(T->rchild,key,T,p);//通过递归查找所给定的关键字,并将查找关键字的父指针赋值给p
}
bool InsertBST(BiTree &T,ElemType key)
{
BiTree p,s;
if(!SearchBST(T,key,NULL,p))
{
s=(BiTree)malloc(sizeof(BiTNode));
s->data=key;
s->lchild=s->rchild=NULL;
if(!p) T=s;
else if(p->data>key) p->lchild=s;//将新生成的节点插入到二叉排序树中
else p->rchild=s;
return true;
}
else return false;
}
bool 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;//保存p的值
s=p->lchild;
while(s->rchild)//查找p的左子树的最大值 
{
q=s;
s=s->rchild;
}
p->data=s->data;//s为被删除节点的前驱,找到p的左子树的最大值赋给p
if(q!=p) q->rchild=s->lchild;//重接q的右子树
else
q->lchild=s->lchild;//重接q的左子树
free(s);
}
return true;
}


void Create(BiTree &T)
{
T=NULL;
}
bool DeleteBST(BiTree &T,ElemType key)
{
if(!T) return false;
else
{
if(T->data==key) 
{
return Delete(T);
}
else if (T->data>key)
{
return DeleteBST(T->lchild,key);
}
else
return DeleteBST(T->rchild,key);
}
}


void main()
{
int i,m,key;
BiTree Tree;
Create(Tree);
cout<<"please input the mount of the number:"<<endl;
cin>>m;
cout<<"please input the data:"<<endl;
for(i=0;i<m;i++) 
{
cin>>key;
InsertBST(Tree,key);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值