本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。
输入格式:
第一行给出正整数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>
#include<malloc.h>
//树节点定义
typedef struct node
{
int data;
struct node *left;
struct node *right;
} node,*tree;
//根据后续和中序遍历创建出树
tree creatTree(int *post,int *in,int n)
{
if(n == 0)
{
return NULL;//没有下一个节点,退出循环
}
int *mid = in;//记录中序遍历的中间根节点
while(*mid != *(post+n-1)) //从中序遍历头结点开始找,找到与后序遍历的最后一个节点元素值相同时退出
{
mid++;
}//退出循环时,mid标记的就是中序遍历的中间根节点
tree t = (tree)malloc(sizeof(node));//建立根节点
t->data = *mid;//将元素值赋给根节点t
//递归遍历左子树和右子树
int leftSize = mid-in;//leftSize代表此时中序遍历根节点左边元素个数
t->left = creatTree(post,in,leftSize);
int rightSize = n-leftSize-1;//rightSize代表此时中序遍历根节点右边元素个数
t->right = creatTree(post+leftSize,in+leftSize+1,rightSize);
return t;
}
//前序打印
void printPre(tree t)
{
if(t)
{
printf(" %d",t->data);
printPre(t->left);
printPre(t->right);
}
}
int main()
{
int post[30],in[30],n;
scanf("%d",&n);//输入节点个数
for(int i = 0; i<n; i++)
{
scanf("%d",&post[i]);//输入后续
}
for(int i = 0; i<n; i++)
{
scanf("%d",&in[i]);//中序输入
}
printf("Preorder:");
tree t = creatTree(post,in,n);
printPre(t);
return 0;
}