您的位置:首页 > 其它

浙大PAT甲级 1102

2016-09-07 17:17 316 查看
反转一个二叉树。先来个广搜再来个中序遍历。

AC代码:

#include<iostream>
#include<map>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
#include<set>
#include<stack>
#include<cmath>
#include<vector>
#include<hash_map>
#define ll long long
#define inf 24*60*60
using namespace std;
struct node
{
int l=-1;
int r=-1;
};
int mark[10];
node a[13];
void bfs(int x)
{
queue<node> q;
q.push(a[x]);
printf("%d",x);
while(!q.empty())
{
node tmp=q.front();
q.pop();
if(tmp.r!=-1)
{
q.push(a[tmp.r]);
printf(" %d",tmp.r);
}
if(tmp.l!=-1)
{
q.push(a[tmp.l]);
printf(" %d",tmp.l);
}
}
printf("\n");
}
int flag=0;
void inorder(int x)
{
if(x==-1)
return;
inorder(a[x].r);
if(flag==0)
{
printf("%d",x);
flag=1;
}
else
{
printf(" %d",x);
}
inorder(a[x].l);
}
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
char b[2];
char d[2];
scanf("%s %s",b,d);
if(b[0]!='-')
{
a[i].l=b[0]-'0';
mark[b[0]-'0']=1;
}
if(d[0]!='-')
{
a[i].r=d[0]-'0';
mark[d[0]-'0']=1;
}
}
int biao;
for(int i=0;i<n;i++)
{
if(mark[i]==0)
{
biao=i;
break;
}
}
bfs(biao);
//cout<<1<<endl;
inorder(biao);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: