静态树存储,找一下根节点,遍历的时候左右节点换一下就可以了
算法笔记上给的方法是:后序遍历时交换左右子树,重建二叉树,再进行遍历
#include<iostream>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
int n;
const int maxn = 20;
struct node {
int lchild, rchild;
}Node[maxn];
bool root[maxn];
vector<int>layer, in;
int convert(char c)
{
if (c == '-')return -1;
else return c - '0';
}
void layerorder(int head)
{
queue<int>q;
q.push(head);
while (!q.empty())
{
int top = q.front();
q.pop();
layer.push_back(top);
if (Node[top].rchild != -1)q.push(Node[top].rchild);
if (Node[top].lchild != -1)q.push(Node[top].lchild);
}
}
void inorder(int head)
{
if (head == -1)return;
inorder(Node[head].rchild);
in.push_back(head);
inorder(Node[head].lchild);
}
void showarr(vector<int>a)
{
for (int i = 0; i < n; i++)
{
printf("%d", a[i]);
if (i != n - 1)printf(" ");
else printf("\n");
}
}
int main()
{
scanf("%d", &n);
for(int i=0;i<n;i++)
{
getchar();
char a, b;
scanf("%c %c", &a, &b);
Node[i].lchild = convert(a);
Node[i].rchild = convert(b);
if (Node[i].lchild >= 0)root[Node[i].lchild] = true;
if (Node[i].rchild >= 0)root[Node[i].rchild] = true;
}
int head;
for (head=0;head<n;head++)
{
if (root[head] == false)break;
}
layerorder(head);
inorder(head);
showarr(layer);
showarr(in);
return 0;
}