浙大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);
}
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);
}
相关文章推荐
- 浙大PAT甲级 1033
- 浙大PAT甲级 1053
- 浙大PAT甲级 1069
- *浙大PAT甲级 1081
- *浙大PAT甲级 1089 归并排序与插入排序
- 浙大PAT甲级 1106 广度优先搜索
- 浙大PAT甲级-1030
- 浙大PAT甲级 1035
- 浙大PAT甲级 1041
- 浙大PAT甲级 1054
- **浙大PAT甲级 1064
- 浙大PAT甲级 1070 贪心
- 浙大PAT甲级 1082
- 浙大PAT甲级 1090 广搜
- **浙大PAT甲级 1103 dfs+快速幂
- *浙大PAT甲级 1110 判断是否为完全二叉树
- 浙大PAT甲级1006
- 浙大PAT甲级-1028
- 浙大pat | 牛客网甲级1063 Count PAT's (25)字符串
- 浙大PAT甲级 1042