题目描述
已知某二叉树的先序序列和中序序列,编程计算并输出该二叉树的后序序列。
输入描述
有多组数据,每组分为两行输入,第一行表示指定二叉树的先序序列,第二行表示该二叉树的中序序列,序列元素均为大写英文字符,表示二叉树的结点。
输出描述
对于每组数组,在一行上输出该二叉树的后序序列。
输入
ABDGCEFH DGBAECHF
输出
GDBEHFCA
#include<bits/stdc++.h>
using namespace std;
typedef struct Node {
char data;
struct Node *lchild;
struct Node *rchild;
Node(char ch) {
data = ch;
lchild = NULL;
rchild = NULL;
}
} Node;
void postOrder(Node *root) {
if (root->lchild) postOrder(root->lchild);
if (root->rchild) postOrder(root->rchild);
cout << root->data;
}
Node *buildTree(string pre, string in) {
int len = pre.length();
if (len <= 0) return NULL;
Node *root = new Node(pre[0]);
int p = in.find(pre[0]);
root->lchild = buildTree(pre.substr(1, p), in.substr(0, p));
root->rchild = buildTree(pre.substr(p+1, len-p-1), in.substr(p+1, len-p-1));
return root;
}
int main() {
string in, pre;
while (cin >> pre) {
cin >> in;
Node *root = buildTree(pre, in);
postOrder(root);
cout << endl;
}
return 0;
}