Solution: binary sort tree

Description Title
input sequence of integer numbers, the number of binary sort established, and the preamble, in sequence, after traversal.

Input
input of the first row comprises an integer n (1 <= n <= 100). The next line comprises n integers.

Output
may be multiple sets of test data for each set of data, the establishment of a binary sort tree to the subject data, and for binary sort tree preamble, sequence and postorder traversals. Each output line through the results. There is a space after the last data of each line.

Sample input
. 1
2
2
. 8 15
. 4
21 is 10. 5 39
sample output
2
2
2
. 8 15
. 8 15
15. 8
21 is 39. 5 10
. 5 10 21 is 39
. 5 10 39 21 is
Features: No repetition number, the left and right small Large
* &: Find modification
*: Find

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Btree{
	int x;
	Btree*left;
	Btree*right;
	Btree()
	{
		left=NULL;
		right=NULL;
	}
};
Btree*root;
int n,vis[10000];
void Insert(int x,Btree *&r)
{
	if(r==NULL)
	{
		r=new Btree;
		r->x=x;
	}
	else
	{
		if(x<r->x)
		 Insert(x,r->left);
		else
		 Insert(x,r->right);
	}
}
void pre(Btree*r)
{
	if(r==NULL) return ;
	cout<<r->x<<" ";
	pre(r->left);
	pre(r->right);
}
void in(Btree*r)
{
	if(r==NULL) return;
	in(r->left);
	cout<<r->x<<" ";
	in(r->right);
}
void pos(Btree*r)
{
	if(r==NULL) return ;
	pos(r->left);
	pos(r->right);
	cout<<r->x<<" ";
}
int Find(int x,Btree*r)
{
	if(r==NULL) return 0;
	if(r->x==x) return 1;
	int left=Find(x,r->left);
	int right=Find(x,r->right);
	return left+right;
}
int main()
{
	while(cin>>n)
	{
		root=NULL;
		for(int i=0;i<n;i++)
		{
			int x;cin>>x;
			if(!Find(x,root)) Insert(x,root);
		}
		pre(root);cout<<endl;
		in(root);cout<<endl;
		pos(root);cout<<endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43540515/article/details/92064912