二叉排序树的实现和查找

 题目:二叉排序树的实现和查找

二叉排序树中,根节点的左子树都小于根节点,右子树都大于根节点(这里没有包含等于的情况,若要包含等于,只需指定等于方向,然后改一下递归的判断条件即可)

        采用依次插入的方式建立二叉排序树

void insert(tree *&p,int n)
{
if(p==NULL)
{
p=new tree;
p->data =n;
p->l =NULL;
p->r =NULL;
return ;
}
else
{
if(n<p->data )
insert(p->l ,n);
else if(n>p->data )
insert(p->r ,n);
}

}

在查找时,也是通过比较当前节点与所求节点的大小来判断递归走向

int time=0;
int flag=0;
void serch(tree *p,int m)
{
if(flag==0)       //还未找到 
if(p==NULL)return ;
time++;
if(p->data ==m)      //已找到,time不再计数 
{
flag=1;
return ;
}
else if(m<p->data )
serch(p->l ,m);
else 
serch(p->r ,m);

}


完整代码:

#include<iostream>
using namespace std;
typedef struct Tree
{
int data;
struct Tree *l;
struct Tree *r;
}tree;
void insert(tree *&p,int n)
{
if(p==NULL)
{
p=new tree;
p->data =n;
p->l =NULL;
p->r =NULL;
return ;
}
else
{
if(n<p->data )
insert(p->l ,n);
else if(n>p->data )
insert(p->r ,n);
}
}
tree *creat(int a[],int n)
{
tree *p=NULL;
for(int i=0;i<n;i++)
insert(p,a[i]);
return p;
}
int flag=0;
void serch(tree *p,int m,int &time)   //这里本来是把time弄成全局变量的,但是交上去报ce了,所以干脆弄成引用传参
{
if(flag==0)//还未找到 
if(p==NULL)return ;
time++;
if(p->data ==m)//已找到,time不再计数 
{
flag=1;
return ;
}
else if(m<p->data )
serch(p->l ,m,time);
else 
serch(p->r ,m,time);
}
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
tree *l=creat(a,n);
int m;
cin>>m;
int time=0;
serch(l,m,time);
if(flag==1)cout<<time;
else cout<<"-1";
return 0;
}

猜你喜欢

转载自blog.csdn.net/acdalao/article/details/80069940
今日推荐