4-15 根据后序和中序遍历输出先序遍历 (15分)
本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。
输入格式:
第一行给出正整数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
思路:
还是通过后序和中序遍历将二叉树还原,之后通过递归输出先序遍历,和4-14 还原二叉树是姊妹题,还原树的思路大致一样,就是注意后序遍历的根结点是和先序恰反,得倒着找就行了。
AC代码:
#include<bits/stdc++.h>
using namespace std;
int flag = 0;
typedef struct btnode{
int data;
struct btnode *left,*right;
}BTnode;
int inod[100],postod[100];
BTnode* Retree(int root,int begin,int end){ //root是后序中的根结点,在后序的末尾,begin是中序的开头,end是中序的结尾
if(begin > end)
return NULL;
BTnode *node = new BTnode;
node->data = postod[root];
int i;
for(i = begin;inod[i]!=postod[root];i++); //找到中序中根结点的位置
node->left = Retree(root - 1 - (end - i),begin,i-1);
node->right = Retree(root - 1,i+1,end);
return node;
}
void print(BTnode *bt){
if(bt == NULL)
return ;
if(flag++)
{
cout << " " << bt->data;
}
else
cout << bt->data;
print(bt->left);
print(bt->right);
}
int main(){
int n;
cin >> n;
for(int i = 0;i < n;i++)
cin >> postod[i];
for(int i = 0;i < n;i++)
cin >> inod[i];
cout << "Preorder: ";
print(Retree(n-1,0,n-1)); //注意后序遍历的root应该传入最后一个值才是根结点,与先序恰反
}