题目描述
小明在做数据结构的作业,其中一题是给你一棵二叉树的前序遍历和中序遍历结果,要求你写出这棵二叉树的后序遍历结果。
输入
输入包含多组测试数据。每组输入包含两个字符串,分别表示二叉树的前序遍历和中序遍历结果。每个字符串由不重复的大写字母组成。
输出
对于每组输入,输出对应的二叉树的后续遍历结果。
样例输入
DBACEGF ABCDEFG
BCAD CBAD
样例输出
ACBFGED
CDAB
思路:先根据前序遍历和中序遍历结果重建二叉树,再后续遍历。
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
typedef struct BiNode {
char data;
struct BiNode *lchild, *rchild;
} BiNode, *BiTree;
string pre, in;
BiTree create(int preL, int preR, int inL, int inR) {
if (preL > preR) {
return nullptr;
}
BiNode *root = new BiNode;
root->data = pre[preL];
int k;
for (k = inL; k <= inR; k++) { //找到根节点在中序遍历中的位置
if (in[k] == pre[preL]) {
break;
}
}
int numLeft = k - inL;
//分别对左右子树递归处理
root->lchild = create(preL + 1, preL + numLeft, inL, k - 1);
root->rchild = create(preL + numLeft + 1, preR, k + 1, inR);
return root;
}
void postorder(BiTree root) {
if (root == nullptr) {
return;
}
postorder(root->lchild);
postorder(root->rchild);
printf("%c", root->data);
}
int main() {
while (cin >> pre >> in) {
BiTree root = create(0, pre.length()-1, 0, in.length()-1);
postorder(root);
printf("\n");
}
}