问题 C: 二叉树遍历 (c++引用版)

题目描述

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

输入

两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。

输出

输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。

样例输入 Copy

ABC
CBA
ABCDEFG
DCBAEFG

样例输出 Copy

CBA
DCBGFEA

#include<iostream>
#include<algorithm>
#include<vector> 
#include<cstring>
#include<string.h>
#include<queue> 
#include<map>
#include<cmath>
#define OK 1
#define ERROR 0
#define MAX 100020
const double eps=1e-5;
const int maxn=1010;
#define MAXSIZE 110
typedef long long LL;
using namespace std;

string st,tt;
typedef struct BiTNode{
    char data;
    struct BiTNode *lchild,*rchild;     
}BiTNode,*BiTree; 

void CreateBiTree(BiTree &T,int lst,int rst,int ltt,int rtt){
    if(lst>rst){
        T=NULL;
    }
    else{
        T=new BiTNode;
        T->data=st[lst];
        int k;
        for(k=ltt;k<=rtt;k++){
            if(tt[k]==st[lst]){
                break;
            }
        }
        int num=k-ltt;
        CreateBiTree(T->lchild,lst+1,lst+num,ltt,k-1);
        CreateBiTree(T->rchild,lst+num+1,rst,k+1,rtt); 
    }
    
    
}
void InOrderTraverse(BiTree T){
    if(T){
        InOrderTraverse(T->lchild);
        InOrderTraverse(T->rchild);
        cout<<T->data;
    }
}

int main(){
    
    BiTree T;
    while(cin>>st){
        cin>>tt;
        CreateBiTree(T,0,st.length()-1,0,tt.length()-1);
        InOrderTraverse(T);
        cout<<endl;
    }
    
    return 0;
} 
原文地址:https://www.cnblogs.com/dreamzj/p/13681609.html