7-2 根据后序和中序遍历输出先序遍历 (25 分)
本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。
输入格式:
第一行给出正整数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 <bits/stdc++.h>
using namespace std;
struct treeNode{
int Data;
struct treeNode *right;
struct treeNode *left;
};
typedef struct treeNode* Node;
Node createTree(int *X,int *Z,int temp){
Node root=(Node)malloc(sizeof(struct treeNode));
if(temp==0)return NULL;
root->left=NULL;
root->right=NULL;
root->Data=*(X+temp-1);
int k;
for(int i=0;i<temp;i++){
if(*(X+temp-1)==*(Z+i))
{k=i;break;}
}
root->left=createTree(X,Z,k);
root->right=createTree(X+k,Z+k+1,temp-k-1);
return root;
}
void qianxubianli(Node root)
{
if(root==NULL)return;
cout<<" "<<root->Data;
qianxubianli(root->left);
qianxubianli(root->right);
}
int main()
{
int N;
cin>>N;
int hx[N];
int zx[N];
for(int i=0;i<N;i++)
cin>>hx[i];
for(int i=0;i<N;i++)
cin>>zx[i];
Node Root=createTree(hx,zx,N);
cout<<"Preorder:";
qianxubianli(Root);
return 0;
}