二叉排序树之创建、查找、插入、修改
作者:互联网
资料:二叉排序树
建议看完资料后看代码会异常清晰!!!
代码:
#include<iostream>
using namespace std;
int n,a[1010];
typedef struct node
{
int key;
int data;
struct node *lchild,*rchild;
}BSTNode;//节点
void insertbst(BSTNode *&bt,int k)//插入
{
if(bt==NULL)
{
bt=new node;
bt->key=k;
bt->lchild=bt->rchild=NULL;
}
else
{
if(k<bt->key)insertbst(bt->lchild,k);
else if(k>bt->key)insertbst(bt->rchild,k);
}
}
BSTNode *find(BSTNode *&bt,int k)//查找
{
if(bt==NULL||bt->key==k)
{
return bt;
}
else if(k<bt->key)return find(bt->lchild,k);
else if(k>bt->key)return find(bt->rchild,k);
}
BSTNode *find1(BSTNode *&bt,int k,BSTNode *f1,BSTNode *&f)//查找要找的关键字的父亲节点
{
if(bt==NULL)
{
f=NULL;
return NULL;
}
else if(k==bt->key)
{
f=f1;
printf("%d\n",f->key);
return bt;
}
else if(k<bt->key)return find1(bt->lchild,k,bt,f);
else if(k>bt->key)return find1(bt->rchild,k,bt,f);
//f1用做记录f
}
void deletep(BSTNode *&p);
void deletel(BSTNode *&p,BSTNode *&r);
void Delete(BSTNode *&bt,int k)//删除
{
if(bt==NULL)return ;
else if(k<bt->key)Delete(bt->lchild,k);
else if(k>bt->key)Delete(bt->rchild,k);
else if(k==bt->key)
{
deletep(bt);
}
}
void deletep(BSTNode *&p)//分三种情况
{
BSTNode *q;
if(p->lchild==NULL)
{
q=p;
p=p->rchild;
delete q;
}
else if(p->rchild==NULL)
{
q=p;
p=p->lchild;
delete q;
}
else deletel(p,p->lchild);
}
void deletel(BSTNode *&p,BSTNode *&r)//删除既有左子树,有右子树的节点
{
if(r->rchild!=NULL)
{
deletel(p,r->rchild);
}
else
{
BSTNode *q;
p->key=r->key;
q=r;
r=r->lchild;
delete q;
}
}
void print(BSTNode *&bt)//输出排序
{
if(bt==NULL)
{
return ;
}
print(bt->lchild);
printf("%d ",bt->key);
print(bt->rchild);
}
int main()
{
//不能输入同样的数字
BSTNode *bt=NULL,*q,*f=NULL;
f=new node;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
for(int i=0;i<n;i++)
{
insertbst(bt,a[i]);
}
insertbst(bt,50);
print(bt);
printf("\n");
q=find(bt,50);
printf("%d\n",q->key);
q=find1(bt,50,NULL,f);
//printf("%d %d\n",q->key,f->key);
Delete(bt,0);
print(bt);
printf("\n");
return 0;
}
标签:NULL,BSTNode,二叉,bt,else,查找,key,rchild,排序 来源: https://blog.csdn.net/weixin_46627433/article/details/110500110