Implementation and search of binary sorted tree

 Title: Implementation and Search of Binary Sort Trees

In a binary sorting tree, the left subtree of the root node is smaller than the root node, and the right subtree is larger than the root node (there is no equal case here, if you want to include equals, you only need to specify the equal direction, and then change the recursive judgment condition can)

        Build a binary sorting tree by inserting sequentially

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);
}

}

When searching, the recursive direction is also judged by comparing the size of the current node and the desired node.

int time=0;
int flag=0;
void serch(tree *p,int m)
{
if(flag==0) //not found 
if(p==NULL)return ;
time++;
if(p->data ==m) //Found, time no longer counts 
{
flag=1;
return ;
}
else if(m<p->data )
serch(p->l ,m);
else 
serch(p->r ,m );

}


Full code:

#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) //Originally, time was made a global variable here, but it was reported to ce, so it was simply passed as a reference
{
if(flag==0)// not found 
if(p==NULL)return ;
time++;
if(p->data ==m)//found, time no longer counts 
{
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;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324787488&siteId=291194637