#include<iostream>
#include<string>
#include<queue>
#include<vector>
using namespace std;
struct node{
int id, l, r;
}a[100];
vector<int> vIn, vLe;
void levelOrder(int root){
queue<int> q;
q.push(root);
while(!q.empty()){
int top = q.front();
vLe.push_back(top);
q.pop();
if(a[top].l != -1) q.push(a[top].l);
if(a[top].r != -1) q.push(a[top].r);
}
}
void inOrder(int root){
if(root == -1){
return;
}
inOrder(a[root].l);
vIn.push_back(root);
inOrder(a[root].r);
}
int main(){
int n, root = 0, have[100] = {0};
cin >> n;
for(int i = 0; i < n; i++){
string l, r;
a[i].id = i;
cin >> l >> r;
if(l != "-"){
a[i].r = stoi(l);
have[stoi(l)] = 1;
}else{
a[i].r = -1;
}
if(r != "-"){
a[i].l = stoi(r);
have[stoi(r)] = 1;
}else{
a[i].l = -1;
}
}
while(have[root] == 1) root++;
levelOrder(root);
inOrder(root);
for(int i = 0; i < n; i++){
if(i != 0) printf(" ");
printf("%d", vLe[i]);
}
cout << endl;
for(int i = 0; i < n; i++){
if(i != 0) printf(" ");
printf("%d", vIn[i]);
}
return 0;
}
A1102 Invert a Binary Tree (25分)(二叉树的中序遍历和层序遍历、静态二叉树的创建)
原文:https://www.cnblogs.com/tsruixi/p/13227535.html