PTA7-1 根据后序和中序遍历输出先序遍历

本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。
输入格式:
第一行给出正整数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 btnode *btlink;
struct btnode{
	int element;
	btlink left,right;
};//根据书上的示例建立二叉树结点结构
struct btnode *create(int a[],int b[],int n){//a是中序,b是后序,n记录每一个子树的长度
	if(n<=0)return NULL;
	int i=0;
	while(a[i]!=b[n-1]){
		i++;
	}
	struct btnode *T;
	T=(struct btnode*)malloc(sizeof(struct btnode));
	T->left=create(a,b,i);//左子树在数列中相对位置一直在左边
	T->right=create(a+i+1,b+i,n-i-1);//右子树在数列中相对位置一直在右边,并且将代表右子树的一段数列分离开来
	T->element=b[n-1];
	return T;
}//用递归的方法来建立子树
void preorder(struct btnode *root){
	if(root){
		printf(" %d",root->element);
		if(root->left)preorder(root->left);
		if(root->right)preorder(root->right);
	}
}//先序遍历
int main()
{
	int N,i,post[35],in[35];
	scanf("%d",&N);
	for(i=0;i<N;i++)scanf("%d",&post[i]);
	for(i=0;i<N;i++)scanf("%d",&in[i]);
	struct btnode *T;
	T=create(in,post,N);
	printf("Preorder:");
	preorder(T);
	return 0;
 } 
原文地址:https://www.cnblogs.com/ponynice/p/13829592.html