按表建树,
然后层序按 先右子树再左子树的顺序进队列,
中序按 右中左的顺序遍历就是翻转后的。
#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#define MAX 15
#define null -1
using namespace std;
int n;
struct Node {
int left;
int right;
};
Node t[MAX];
bool isVis[MAX];
vector <int> level;
vector <int> in;
int str2int(string s) {
int sum = 0;
for (int i = 0; i < s.size(); i++) {
sum *= 10;
sum += s[i] - '0';
}
return sum;
}
void LevelOrder(int root) {
queue <int> q;
if (root != null) {
q.push(root);
level.push_back(root);
}
while (!q.empty()) {
int data = q.front();
q.pop();
if (t[data].right != null) {
q.push(t[data].right);
level.push_back(t[data].right);
}
if (t[data].left != null) {
q.push(t[data].left);
level.push_back(t[data].left);
}
}
}
void InOrder(int root) {
if (root != null) {
InOrder(t[root].right);
in.push_back(root);
InOrder(t[root].left);
}
}
int main() {
cin >> n;
string left, right;
for (int i = 0; i < n; i++) {
cin >> left >> right;
if (left[0] != '-') {
t[i].left = str2int(left);
isVis[t[i].left] = true;
}
else
t[i].left = null;
if (right[0] != '-') {
t[i].right = str2int(right);
isVis[t[i].right] = true;
}
else
t[i].right = null;
}
int root = -1;
for (int i = 0; i < n; i++) {
if (!isVis[i])
root = i;
}
LevelOrder(root);
InOrder(root);
cout << level[0];
for (int i = 1; i < n; i++) {
cout << " " << level[i];
}
cout << endl;
cout << in[0];
for (int i = 1; i < n; i++) {
cout << " " << in[i];
}
cout << endl;
return 0;
}