pat 1138

1138 Postorder Traversal (25分)

 

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 (≤ 50,000), 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

题意:给定一个二叉树的前序和中序遍历序列,求后续遍历序列的第一个结点

思路:根据前序和中序序列建立二叉树,后续遍历到第一个结点之后终止遍历。更多建树方法参考三种建树方法

代码如下:

#include<cstdio>
#include<cstdlib>
int pre[50005];
int in[50005];
struct node{
    int val;
    node* l;
    node* r;
};
void postOrder(node* root,int& mark){
    if(mark==1)
        return;
    if(root){
        postOrder(root->l,mark);
        if(mark==1)
        return;
        postOrder(root->r,mark);
        if(mark==1)
        return;
        printf("%d",root->val);
        mark=1;
        if(mark==1)
        return;
    }
}
node* build(int preL,int preR,int inL,int inR){
    if(preL>preR)
        return NULL;
    node* root=(node*)malloc(sizeof(node));
    int val=pre[preL];
    root->val=val;
    int x;
    for(int i=inL;i<=inR;i++){
        if(in[i]==val){
            x=i;
            break;
        }
    }
    x=x-inL;
    root->l=build(preL+1,preL+x,inL,inL+x-1);
    root->r=build(preL+1+x,preR,inL+x+1,inR);
    return root;
}
int main(){
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",&pre[i]);
    }
    for(int i=0;i<n;i++){
        scanf("%d",&in[i]);
    }
    node* root=build(0,n-1,0,n-1);
    int mark=0;
    postOrder(root,mark);
    return 0;
}
原文地址:https://www.cnblogs.com/foodie-nils/p/13288638.html