hdu-3999 BST
zjhl2
posted @ 2015年7月31日 00:10
with tags
平衡树
, 427 阅读
第一次打BST,不会打便去网上搜模板,可是都写得好复杂,让刚入门C++的我很多看不懂。百度百科了一下,了解了思路,自己yy出了代码,原来很短啊。
#include<cstdio>
#include<cstring>
using namespace std;
int n,i,tot,x;
struct node{
int l,r,v;
}a[100005];
bool first;
void ins(int t)
{
if (a[t].v==0) {a[t].v=x;return;}
if (x<=a[t].v)
{
if (a[t].l==0) {tot++; a[t].l=tot;}
ins(a[t].l);
}
else
{
if (a[t].r==0) {tot++; a[t].r=tot;}
ins(a[t].r);
}
}
void print(int t)
{
if (first) first=0,printf("%d",a[t].v);else printf(" %d",a[t].v);
if (a[t].l) print(a[t].l);
if (a[t].r) print(a[t].r);
}
int main()
{
while(~scanf("%d",&n))
{
memset(a,0,sizeof(a));
tot=1;
for (i=1;i<=n;i++)
{
scanf("%d",&x);
ins(1);
}
first=1;
print(1);
printf("\n");
}
}
评论 (0)