Suppose that all the keys in a binary tree are distinct positive integers. Given the preorder and inorder traversal sequences, you are supposed to output the first number of the postorder traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=50000), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the first number of the postorder traversal sequence of the corresponding binary tree.
Sample Input:
7
1 2 3 4 5 6 7
2 3 1 5 4 7 6
Sample Output:
3
分析:一道简单的前序中序转后序,而且只需要知道后序的第一个值,所以可以定义一个变量flag,当post的第一个值已经输出,则flag为true,递归出口处判断flag,可以提前return
这是一道树的前序中序转后序,基础是递归思想。
例如:
前序遍历: 1234567 根左右
中序遍历: 2315476 左根右
画树求法:
第一步,根据前序遍历的特点,我们知道根结点为1
第二步,观察中序遍历2315476。其中root节点1左侧的23必然是root的左子树,1右侧的5476必然是root的右子树。
第三步,观察左子树23,左子树的中的根节点必然是大树的root的leftchild。在前序遍历中,大树的root的leftchild位于root之后,所以左子树的根节点为2。
第四步,同样的道理,root的右子树节点5476中的根节点也可以通过前序遍历求得。在前序遍历中,一定是先把root和root的所有左子树节点遍历完之后才会遍历右子树,并且遍历的左子树的第一个节点就是左子树的根节点。同理,遍历的右子树的第一个节点就是右子树的根节点。
第五步,观察发现,上面的过程是递归的。先找到当前树的根节点,然后划分为左子树,右子树,然后进入左子树重复上面的过程,然后进入右子树重复上面的过程。最后就可以还原一棵树了。该步递归的过程可以简洁表达如下:
1 确定根,确定左子树,确定右子树。
2 在左子树中递归。
3 在右子树中递归。
4 打印当前根。
那么,我们可以画出这个二叉树的形状:
那么,根据后序的遍历规则,我们可以知道,后序遍历顺序为:3257641
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <vector>
#include <cmath>
using namespace std;
#define max(a,b) (((a)>(b))?(a):(b))
vector<int> pre, in;
bool flag=false;
void postOrder(int prel, int prer, int inl, int inr){
if(inl>inr || flag==true){
return;
}
int i=inl;
while(in[i]!=pre[prel]) i++;
postOrder(prel+1, i-1, inl, i-1);
postOrder(prel+i-inl+1, prer, i+1, inr);
//打印出后序遍历
//printf("%d\n", in[i]); //或pre[prel] 即输出根
if(flag==false){
printf("%d\n", in[i]); //或pre[prel] 即输出根
flag=true;
}
}
int main(){
int n, i;
scanf("%d", &n);
pre.resize(n);
in.resize(n);
for(i=0;i<n;i++) scanf("%d", &pre[i]);
for(i=0;i<n;i++) scanf("%d", &in[i]);
postOrder(0, n-1, 0, n-1);
return 0;
}