(来自本人luogu搬迁,图可能挂了,原文见T136513 横看二叉树
T136513 横看二叉树
题目
来看着张图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lXe90UzL-1604578431155)(https://s1.ax1x.com/2020/06/14/txjRUS.png)]
根 | 左 | 右 |
---|---|---|
1 | 2 | 3 |
2 | 空 | 5 |
3 | 空 | 4 |
4 | 空 | 空 |
5 | 空 | 空 |
很显然
来次先序遍历,再不断覆盖就好了
#include <bits/stdc++.h>
struct q{
int left,right,top;
}a[2000];
int Max(int x,int y){return x>y?x:y;}
int l,r,t;
int n;
int m;
int g;
int answer[2000];
void p(int w,int tall){
m=std::max(m,tall);
answer[tall]=w;
if(a[w].left!=-1)p(a[w].left,tall+1);
if(a[w].right!=-1)p(a[w].right,tall+1);
tall--;
return;
}
int getpa(int from){
if(a[from].top==0)
return from;
return getpa(a[from].top);
}
int main(){
scanf("%d",&n);
/* if(n==0){
printf("1163377\n");
return 0;
}老师的神奇的数据*/
if(n==1){
scanf("%d",&t);
printf("%d\n",t);
return 0;
}
for(int i=1;i<=n;i++){
scanf("%d%d%d",&t,&l,&r);
a[t].left=l;
a[t].right=r;
a[r].top=t;
a[l].top=t;
}
p(getpa(t),1);
for(int i=1;i<=m;i++){
printf("%d ",answer[i]);
}
return 0;
}