您的位置:首页 > 其它

二叉搜索树

2016-04-30 18:33 274 查看
递归的实质,就是当进入下一次递归是,数学模型仍然不变,只是范围减小。

以下代码主要运用尾递归。

即返回指针。

//测试样例:30 15 41 50 33 35 34 0
//二叉搜索树
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
typedef int Elemtype;
typedef struct node{
Elemtype data;
struct node *lchild;
struct node *rchild;
}BitTree;
//后序遍历
void PostOrder(BitTree *BST)
{
if(BST)
{
PostOrder(BST->lchild);
PostOrder(BST->rchild);
printf("%3d",BST->data);
}
}
//层次遍历
void levelorder(BitTree *BST)
{
queue<BitTree*> s;
if(BST) s.push(BST);
BitTree *p;
while(!s.empty())
{
p=s.front();
s.pop();
printf("%3d",p->data);
if(p->lchild) s.push(p->lchild);
if(p->rchild) s.push(p->rchild);
}
}
//递归查找
BitTree *Find(BitTree *BST,Elemtype x)
{
if(!BST) return NULL;
if(BST->data>x)
return Find(BST->lchild,x);
else if(BST->data<x)
return Find(BST->rchild,x);
else return BST;
}
//非递归查找
BitTree *IterFind(BitTree *BST,Elemtype x)
{
while(BST)
{
if(BST->data>x)
BST=BST->lchild;
else if(BST->data<x)
BST=BST->rchild;
else return BST;
}
return NULL;
}
//递归查找最小元素
BitTree *Findmin(BitTree *BST)
{
if(!BST) return NULL;
if(BST->lchild==NULL) return BST;
else return Findmin(BST->lchild);
}
//迭代查找最大元素
BitTree *Findmax(BitTree *BST)
{
if(BST)
while(BST->rchild) BST=BST->rchild;
return BST;
}
//插入元素
BitTree *Insert(BitTree *BST,Elemtype x)
{
if(!BST)
{
BST=(BitTree *)malloc(sizeof(BitTree));
BST->data=x;
BST->lchild=BST->rchild=NULL;
}
else{
if(x>BST->data)
BST->rchild=Insert(BST->rchild,x);
else if(x<BST->data)
BST->lchild=Insert(BST->lchild,x);
}
return BST;
}
//删除元素
BitTree *Delete(Elemtype m,BitTree *BST)
{
BitTree *Tmp;
if(!BST) printf("Not find\n");
else if(BST->data>m)
BST->lchild=Delete(m,BST->lchild);
else if(BST->data<m)
BST->rchild=Delete(m,BST->rchild);
else
if(BST->lchild&&BST->rchild)
{
Tmp=Findmax(BST->rchild);
BST->data=Tmp->data;
BST->rchild=Delete(Tmp->data,BST->rchild);
}
else{
Tmp=BST;
if(!BST->lchild)
BST=BST->rchild;
else if(!BST->rchild)
BST=BST->lchild;
free(Tmp);
}
return BST;
}
int main()
{
Elemtype x;
Elemtype y;
BitTree *min,*max,*f;
BitTree *BST = nullptr;
while(cin>>x&&x)
BST=Insert(BST, x);
scanf("%d",&y);
f=Find(BST, y);
min=Findmin(BST);
max=Findmax(BST);
levelorder(BST);
cout<<endl;
printf("%3d",f->data);
printf("%3d",min->data);
printf("%3d",max->data);
printf("\n");
int m;
scanf("%d",&m);
Delete(m,BST);
levelorder(BST);
cout<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: