本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。
输入格式:
第一行给出正整数N(≤30),是树中结点的个数。随后两行,每行给出N个整数,分别对应后序遍历和中序遍历结果,数字间以空格分隔。题目保证输入正确对应一棵二叉树。
输出格式:
在一行中输出Preorder: 以及该树的先序遍历结果。数字间有1个空格,行末不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
Preorder: 4 1 3 2 6 5 7
注意事项
- 由于加边函数的特殊性,若要实现左子树为父节点u的头结点,右子树为其next。我们应该先插入右子树结点再插入左子树结点
- 插入结点前,需用add_edge加边函数创建结点
- 在链式前向星中,NULL用-1代替
#include<stdio.h>
#include<string.h>
#define MaxSize 80
typedef struct Edge {
int to, next; //二叉树无需权重
} Edge;
int head[MaxSize];
int tot = 0;
int i = 0;
int s[MaxSize] = {0};
int N;
//pl为子树在后序序列中的左边界...
void add_edge(Edge edge[], int u, int v) { //u为起点,v为终点,w为权值
edge[tot].to = v; //tot为空结点指针
edge[tot].next = head[u];
head[u] = tot++;//tot为任一个未被使用的空节点指针。
}
void dispose(Edge *root, Edge edge[], int post[], int mid[], int pl, int pr, int ml, int mr) {
root->to = post[pr];
int pos = ml;
int lchild, rchild;
while (mid[pos] != post[pr]) { //找到子树根在中序中的位置
pos++;
}
int lenL = pos - ml;//左子树的长度
if (pos < mr) {//由于插入性质,先右子树
add_edge(edge, root->to, -1);//插入结点编号为root->to的头结点
rchild = head[root->to];
dispose(&edge[rchild], edge, post, mid, pl + lenL, pr - 1, pos + 1, mr);
}
if (pos > ml) {
add_edge(edge, root->to, -1);
lchild = head[root->to];//插入结点编号为root->to的头结点
dispose(&edge[lchild], edge, post, mid, pl, pl + lenL - 1, ml, pos - 1);
}
}
int create(Edge edge[]) {
int post[MaxSize], mid[MaxSize];
scanf("%d", &N);
for (int i = 0; i < N; i++)
scanf("%d", &post[i]);
for (int i = 0; i < N; i++)
scanf("%d", &mid[i]);
dispose(&edge[tot++], edge, post, mid, 0, N - 1, 0, N - 1);//后+中生成树
return post[N - 1];
}
void pre(Edge edge[], int Root) {//前序遍历
if (Root != -1) {
s[i++] = Root;
if (head[Root] != -1)
pre(edge, edge[head[Root]].to);
if (head[Root] != -1 && edge[head[Root]].next != -1)
pre(edge, edge[edge[head[Root]].next].to);
}
return;
}
int main() {
Edge edge[MaxSize];//定义链式前向星
memset(edge, -1, sizeof(Edge)*MaxSize);
memset(head, -1, sizeof(int)*MaxSize);
int Root = create(edge);
pre(edge, Root);
printf("Preorder: ");
for(i=0;i<N-1;i++)
printf("%d ",s[i]);
printf("%d",s[i]);
return 0;
}