二分搜索树

最水的二叉树

#include<iostream>
#include<algorithm>
using namespace std;
int read()
{
	int s=0,f=1;
	char in=getchar();
	while(in<'0'&&in>'9')
	{
		if(in=='-')
			f=-1;
		in=getchar();
	}
	while(in>='0'&&in<='9')
	{
		s=(s<<1)+(s<<3)+in-'0';
		in=getchar();
	}
	return s*f;
}
int data[10000];
struct node
{
	int value;
	int left;
	int right;
	node()
	{
		value=-0x7ffffff;
		left=-1;
		right=-1;
	}
};
node tree[1010];
int tail;
int build(int l,int r)
{
	if(l>r)
		return -1;
	int num=++tail;
	int mid=(l+r)>>1;
	tree[num].value=data[mid];
	tree[num].left=build(l,mid-1);
	tree[num].right=build(mid+1,r);
	return num;
}
void visit(int x)
{
	if(x==-1)
		return ;
	visit(tree[x].left);
	printf("%d ",tree[x].value);
	visit(tree[x].right);
}
int insert(int val,int x)
{
	if(x==-1)
	{
		tree[++tail].value=val;
		return tail;
	}
	if(val<tree[x].value)
	{
		tree[x].left=insert(val,tree[x].left);
		return x;
	}
	else
	{
		tree[x].right=insert(val,tree[x].right);
		return x;
	}
}
int main()
{
	int n=read(),m=read();
	for(int i=1;i<=n;i++)
		data[i]=read();
	sort(data+1,data+1+n);
	build(1,n);
	for(int i=1;i<=m;i++)
		insert(read(),1);
	visit(1);
}
posted @ 2018-04-16 21:32  Lance1ot  阅读(147)  评论(0编辑  收藏  举报