二叉树遍历(暑假每日一题 23)

假定一棵二叉树的每个结点都用一个大写字母描述。

给定这棵二叉树的前序遍历和中序遍历,求其后序遍历。

输入格式
输入包含多组测试数据。

每组数据占两行,每行包含一个大写字母构成的字符串,第一行表示二叉树的前序遍历,第二行表示二叉树的中序遍历。

输出格式
每组数据输出一行,一个字符串,表示二叉树的后序遍历。

数据范围
输入字符串的长度均不超过 26 26 26

输入样例:

ABC
BAC
FDXEAG
XDEFAG

输出样例:

BCA
XEDGAF

#include<iostream>

using namespace std;

const int N = 30;

string a, b;
int l[N], r[N], pos[N];

void build_tree(int il, int ir, int pl, int pr){
    
    
    
    int root = a[pl] - 'A';
    int p = pos[root];
    if(il < p) build_tree(il, p - 1, pl + 1, pl + 1 + p - 1 - il);
    if(p < ir) build_tree(p + 1, ir, pl + 1 + p - 1 - il + 1, pr);
    cout << a[pl];
}

int main(){
    
    
    
    while(cin >> a >> b){
    
    
        
        int n = a.size();
        for(int i = 0; i < n; i++)
            pos[b[i] - 'A'] = i;
        build_tree(0, n - 1, 0, n - 1);
        puts("");
    }
    
}

猜你喜欢

转载自blog.csdn.net/qq_46456049/article/details/126322173