二叉搜索树模板程序,建立、遍历,可以直接复制粘贴(非ACM模板)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Yonggie/article/details/89401906
#include <iostream>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <cstdlib> 
using namespace std;
const int N=20;
//t means tree for short.
//l means left child's index, r means right child's index.
//as linear data all we need to do is to modify l array and r array.
int t[N+5];
int l[N],r[N];
int f,root;

//we recurse until we find a suitable place.
void insert(int index,int x)
{
	//if values is less or equal to 
	if(x<=t[index])
	{
		//if it has no index, the inserted value will be its leaf.
		if(l[index]==-1) l[index]=f;
		//if not, it means it has left child, recurse until leaves.
		else insert(l[index],x);
	}
	else//this is for its right child, similiar to annotation above.
	{
		if(r[index]==-1) r[index]=f;
		else insert(r[index],x);
	}
}

//output data as inorder also as ascending order.
void in_order_a(int i) 
{
	if(l[i]!=-1) in_order_a(l[i]);
	printf("%d ",t[i]);
	if(r[i]!=-1) in_order_a(r[i]);
}
//output data as inorder as deascending order.
void in_order_d(int i)
{
	 if(r[i]!=-1) in_order_d(r[i]);
	 printf("%d ",t[i]);
	 if(l[i]!=-1) in_order_d(l[i]);
}
void create()
{
	//initialize
	memset(t,0,sizeof(t));
	memset(l,-1,sizeof(l));
	memset(r,-1,sizeof(r));
	f=0;
	root=-1;
	
	//insert 20 numbers as initial data.
	for(int i=0;i<N;i++)
	{
		int n=rand()%50;
		cout<<n<<endl;
		//insert into root place when it's first time.
		if(root==-1) t[++root]=n;
		else
		{
			t[++f]=n;
			//modify array
			insert(root,n);
		} 
	}
}

void search(int i, int k)
{
	if(t[i]==k) {cout<<"we find it!\n"; return;}
	else if(k<t[i]) 
	{
		if(l[i]!=-1) search(l[i],k);
		return;
	}
	else if(k>t[i])
	{
		if(r[i]!=-1) search(r[i],k);
		return;
	}
	cout<<"we didnt find it!\n";
		
	
}
int main()
{
	srand(unsigned(time(NULL)));
	
	//create tree;
 	create();
 	
 	cout<<"ascending output:\n";
 	in_order_a(root) ;
 	
 	cout<<endl<<endl;

 	cout<<"deascending output:\n";
 	in_order_d(root);
 	
    cout<<endl ;
 	
 	cout<<"now give me a number\n" ;
 	int x;
 	cin>>x;
 	search(root,x);
}

猜你喜欢

转载自blog.csdn.net/Yonggie/article/details/89401906