二叉树(根据先序序列以及中序序列求后序遍历序列)

题目描述

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

输入描述:

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

输出描述:

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

输入

ABC
BAC
FDXEAG
XDEFAG

输出

BCA
XEDGAF

#include<iostream>
using namespace std;
string before,mid;
struct node
{
    char c;
    node * lchild;
    node * rchild;
}Tree[30];
int size=0;
node *create()
{
    Tree[size].lchild=Tree[size].rchild;
    return &Tree[size++];
}
void post(node* tree)
{
    if(tree->lchild)post(tree->lchild);
    if(tree->rchild)post(tree->rchild);
    cout<<tree->c;
}
node* build(int s1,int e1,int s2,int e2)
{
    node *ret=create();
    int root;
    ret->c=before[s1];
    for(int i=s2;i<=e2;i++)
    {
        if(before[s1]==mid[i])
        {
            root=i;
            break;
        }
    }
    if(root!=s2)//说明是有左子树的
    {
        ret->lchild=build(s1+1,s1+root-s2,s2,root-1);
    }
    if(root!=e2) //说明是有右子树的
    {
        ret->rchild=build(s1+root-s2+1,e1,root+1,e2);
    }
    return ret;


}
int main()
{

    while(cin>>before>>mid)
    {
       int len1=before.size();
       int len2=mid.size();
       size=0;
       node* tree = build(0,len1-1,0,len2-1);
       post(tree);
       cout<<endl;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38030194/article/details/80310675