由前序遍历和中序遍历确定二叉树

问题 B: 二叉树的遍历

时间限制: 1 Sec  内存限制: 128 MB
提交: 582  解决: 331
[提交][状态][讨论版]

题目描述

根据二叉树性质,由二叉树的前序遍历序和中序遍历序,可以唯一确定一棵二叉树(设二叉树中各结点不相同)。请编写程序,根据输入的二叉树的前序遍历序和中序遍历序,计算并输出其后序遍历序。

输入

输入第一行为二叉树的个数n,0<n≤1000,其后n行每行中由两个字符串组成,第一个是二叉树的前序遍历序,第二个是二叉树的中序遍历序,字符串中每个字符表示一个结点,字符串长度不超过2000。

输出

对每个二叉树,输出一行后序遍历序。

样例输入

2
abc bac
ab ba

样例输出

bca
ba


#include "bits/stdc++.h"
using namespace std;
typedef struct tree1
{
    char data;
    tree1 *leftchild;
    tree1 *rightchild;
}*Tree1;
void creattree1(Tree1 &T,string s1,string s2)
{
    if(s1.length() == 0)
    {
        T = NULL;
        return;
    }
    char roots  = s1[0];
    int position = s2.find(roots);
    string leftstr2 = s2.substr(0,position);
    string rightstr2 = s2.substr(position+1);

    int lenleft = leftstr2.length();
    int lenright = rightstr2.length();

    string leftstr1 = s1.substr(1,lenleft);
    string rightstr1 = s1.substr(lenleft+1);

    T = (Tree1)malloc(sizeof(tree1));
    if(T != NULL)
    {
        T->data = roots;
        creattree1(T->leftchild,leftstr1,leftstr2);
        creattree1(T->rightchild,rightstr1,rightstr2);
    }
}

void houxubianli(Tree1 &T)
{
    if(T == NULL)
        return;
    houxubianli(T->leftchild);
    houxubianli(T->rightchild);
    cout << T->data;
}

int main()
{
    int n;
    cin >> n;
    while(n--)
    {
        Tree1 T;
        string s1,s2;
        cin >> s1 >> s2;
        creattree1(T,s1,s2);
        houxubianli(T);
        cout <<endl;
    }
    return 0;
}

思想是递归,蛮难想的,半抄半写。

    原文作者:算法小白
    原文地址: https://www.cnblogs.com/cunyusup/p/7998531.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞