本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。
输入格式:
第一行给出正整数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
#include<stdio.h>
#include<stdlib.h>
typedef struct BiTNode {
char data;
struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
int i=0;
int s[40]={0};
void pre(BiTree T) {
if (T!= NULL) {
s[i++]=T->data;
pre(T->lchild);
pre(T->rchild);
} else
return;
}
void dispose(BiTree &T, int post[], int mid[], int pl, int pr, int ml, int mr) {
T = (BiTNode *)malloc(sizeof(BiTNode));
T->data = post[pr];
T->lchild = T->rchild = NULL;
int pos = ml;
while (mid[pos] != post[pr])
pos++;
int lenthL = pos - ml;//左子树的长度
if (pos > ml) //左子树
dispose(T->lchild, post, mid, pl, pl + lenthL - 1, ml, pos-1);
//左子树,中缀的结尾移动到中缀中结点的左边,后缀的结尾移动到开头+lenthL-1处
if (pos < mr) //右子树
dispose(T->rchild, post, mid, pl+lenthL, pr-1,pos+1, mr);
}
int main() {
BiTree T;
int post[40] = {0};
int mid[40] = {0};
int length = 0;
int j=0;
scanf("%d", &length);
for (int i = 0; i < length; i++)
scanf("%d", &post[i]);
for (int i = 0; i < length; i++)
scanf("%d", &mid[i]);
dispose(T, post, mid, 0, length - 1, 0, length - 1);
pre(T);
for(j=0;j<length-1;j++)
printf("%d ",s[j]);
printf("%d",s[j]);
return 0;
}

博客围绕根据给定二叉树的后序遍历和中序遍历结果,输出其先序遍历结果展开。介绍了输入格式,需给出树中结点个数及后序、中序遍历结果;也说明了输出格式,要输出Preorder: 及先序遍历结果。
728

被折叠的 条评论
为什么被折叠?



