这道题感觉挺有意思的,考查了二叉树的层序遍历和中序遍历。
需要注意的地方:
1.标记空结点
2.交换左右子树后层序遍历和中序遍历
3.找树根
#include<cstdio>
#include<vector>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
vector<int> child[15],level,in;
void levelorder(int root){
queue<int> q;
q.push(root);
while(!q.empty()){
int tmp = q.front();
q.pop();
level.push_back(tmp);
for(int i=1;i>=0;i--){
if(child[tmp][i] != -1) q.push(child[tmp][i]);
}
}
}
void inorder(int root){
if(root == -1) return;
inorder(child[root][1]);
in.push_back(root);
inorder(child[root][0]);
}
int start[15];
int main(){
int n;
char left,right;
memset(start,-1,sizeof(start));
scanf("%d",&n);
for(int i=0;i<n;i++){
getchar();
scanf("%c %c",&left,&right);
if(left >='0' && left <= 10 +'0'){
child[i].push_back(left-'0');
start[left-'0']=i;
}else{
child[i].push_back(-1);
start[left-'0']=i;
}
if(right >='0' && right <= 10 + '0'){
child[i].push_back(right - '0');
start[right-'0']=i;
}else{
child[i].push_back(-1);
start[right-'0']=i;
}
}
int root=0;
for(int i=0;i<n;i++){
if(start[i]==-1){
root = i;
break;
}
}
//printf("%d\n",root);
levelorder(root);
inorder(root);
for(int i=0;i<level.size();i++){
if(i>0) printf(" ");
printf("%d",level[i]);
}
putchar(10);
for(int i=0;i<in.size();i++){
if(i>0) printf(" ");
printf("%d",in[i]);
}
return 0;
}