二叉树的前序、中序、后序遍历的定义: 前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树; 中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树; 后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。 给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。

#include <stdio.h>
#include <stdlib.h>
#include<cstdio>
#include<algorithm>
#include <iostream>
#include<stack>
#include <string.h>
using namespace std;
//1 确定根,确定左子树,确定右子树。
//2 在左子树中递归。
//3 在右子树中递归。
//4 打印当前根。
char pre[100],mid[100];
struct node{
    char key;
    node *left,*right;
}Tree[50];
int loc=0;
node *Creat(){
    Tree[loc].left=Tree[loc].right=nullptr;
    return &Tree[loc++];
}
node *Build(int s1,int e1,int s2,int e2){
    node *ans=Creat();
    ans->key=pre[s1];
    int root_index;
    for(int i=s2;i<=e2;i++){
        if(mid[i]==pre[s1]){
            root_index=i;
            break;
        }
    }
    if(root_index!=s2){
        ans->left=Build(s1+1,s1+(root_index-s2),s2,root_index-1);

    }
    if(root_index!=e2){
        ans->right=Build(s1+(root_index-s2)+1,e1,root_index+1,e2);
    }
    return ans;
}
void postOrder(node *T){
    if(T==nullptr) return;
    postOrder(T->left);
    postOrder(T->right);
    printf("%c",T->key);
}
int main(){
    while(scanf("%s",pre)!=EOF){
        scanf("%s",mid);
        loc=0;
        int len1=strlen(pre);
        int len2=strlen(mid);
        node *T=Build(0,len1-1,0,len2-1);
        postOrder(T);
        cout<<endl;
    }
    return 0;
}

  

posted on 2018-06-02 11:03  Sunshine&暖阳  阅读(189)  评论(0编辑  收藏  举报