层次遍历先输出右节点
(原来以为是先输出大的 提交以后有一个错误 测试点1 仔细看过代码后发现没错误就觉得是这个问题 一试就成功)
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
#define maxsize 100001
#define min(a,b) a<b?a:b
struct tree{
char left;
char right;
}a[10];
int first=0;
void Swap(char *a,char *b)
{
char t=*a;
*a=*b;
*b=t;
}
void levelorder(int root,tree a[])
{
queue<int> q;
q.push(root);
int t;
while(!q.empty())
{
t=q.front();
if(t==root)
printf("%d",t);
else
printf(" %d",t);
q.pop();
if(a[t].left!='-'&&a[t].right!='-')
{
q.push(a[t].right-'0');
q.push(a[t].left-'0');
}
else if(a[t].left!='-'&&a[t].right=='-')
q.push(a[t].left-'0');
else if(a[t].left=='-'&&a[t].right!='-')
q.push(a[t].right-'0');
if(a[t].left!=a[t].right)
Swap(&a[t].left,&a[t].right);//直接在层次遍历中实现调换
}
printf("\n");
}
void inorder(tree a[],int index)
{
if(a[index].left!='-')
inorder(a,a[index].left-'0');
if(!first)
{
printf("%d",index);
first++;
}
else
printf(" %d",index);
if(a[index].right!='-')
inorder(a,a[index].right-'0');
}
int main()
{
int n;
int b[10]={0};
scanf("%d",&n);
for(int i=0;i<n;i++)
{getchar();
scanf("%c %c",&a[i].left,&a[i].right);
if(a[i].left!='-')
b[a[i].left-'0']=1;
if(a[i].right!='-')
b[a[i].right-'0']=1;
}
int root;
for(int i=0;i<n;i++)
if(!b[i])
{
root=i;
break;
}
levelorder(root,a);
inorder(a,root);
return 0;
}