code:
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <stdexcept>
#include<algorithm>
#include<stack>
#include<queue>
#include<functional>
struct Node {
Node*lchild;
Node*rchild;
char data;
}Tree[50];
int loc;
// 创建一个节点
Node*create()
{
Tree[loc].lchild = Tree[loc].rchild = NULL;
return &Tree[loc++];
}
char str1[30], str2[30];
// 后续遍历
void postOrder(Node*T)
{
if (T->lchild != NULL)
postOrder(T->lchild);
if (T->rchild != NULL)
postOrder(T->rchild);
printf("%c", T->data);
}
// 中序遍历
void midOrder(Node*T)
{
if (T->lchild != NULL)
midOrder(T->lchild);
printf("%c", T->data);
if (T->rchild != NULL)
midOrder(T->rchild);
}
// 前序遍历
void preOrder(Node*T)
{
printf("%c", T->data);
if (T->lchild != NULL)
preOrder(T->lchild);
if (T->rchild != NULL)
preOrder(T->rchild);
}
// 根据前序和中序序列还原二叉树
// 返回还原的二叉树的根节点
Node*build(int s1, int e1, int s2, int e2)
{
// 创建根节点,申请空间
Node*root = create();
root->data = str1[s1];
int rootIdx;
// 前序遍历的当前节点在中序遍历中的位置
for (int i = s2; i <= e2; i++)
{
if (str2[i] == str1[s1])
{
rootIdx = i;
break;
}
}
// 中序序列中的当前节点的左子树非空
if (rootIdx != s2)
root->lchild = build(s1 + 1, s1 + (rootIdx - s2), s2, rootIdx - 1);
// 中序序列中的当前节点的右子树非空
if (rootIdx != e2)
root->rchild = build(s1 + (rootIdx - s2) + 1, e1, rootIdx + 1, e2);
return root;
}
void get_postOrder()
{
int x;
scanf_s("%d", &x);
while (x)
{
std::cin >> str1;
std::cin >> str2;
loc = 0;
int l1 = strlen(str1);
int l2 = strlen(str2);
Node*T = build2(0, l1 - 1, 0, l2 - 1);
preOrder(T);
printf("\n");
scanf_s("%d", &x);
}
}
int main(void)
{
get_postOrder();
system("pause");
return 0;
}