Problem Description
二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)
Input Description
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。
Output Description
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。
Sample Input
ABC CBA ABCDEFG DCBAEFG
Sample Output
CBA DCBGFEA
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
using namespace std;
#define Max 27 // 串的最大长度
char qianxu[Max];
char zhonxu[Max];
char houxu[Max];
struct node
{
char ch;
struct node *lc;
struct node *rc;
};
node* hou(int b1, int e1, int b2, int e2)
{
node* newNode = (node *)malloc(sizeof(node));
newNode->lc = newNode->rc = NULL;
newNode->ch = qianxu[b1];
int ri = -1;
for(int i = b2 ; i <= e2 ; i++ )
{
if(qianxu[b1] == zhonxu[i])
{
ri = i;
break;
}
}
if(ri != b2)
{
newNode->lc = hou(b1 + 1, b1 + (ri - b2), b2, ri - 1);
}
if(ri != e2)
{
newNode->rc = hou(b1 + (ri - b2) + 1, e1, ri + 1, e2);
}
return newNode;
}
node* qian(int b1, int e1, int b2, int e2)
{
node* newNode = (node *)malloc(sizeof(node));
newNode->lc = newNode->rc = NULL;
newNode->ch = qianxu[e2];
int ri = 0;
for(int i = b1 ; i <= e1 ; i++ )
{
if(houxu[i] == zhonxu[i])
{
ri = i;
break;
}
}
if(ri != b1)
{
newNode->lc = qian(b1, ri - 1, b2, b2 + (ri - b1) - 1);
}
if(ri != e1)
{
newNode->rc = qian(ri + 1, e1, b2 + (ri - b1) , e2 - 1);
}
return newNode;
}
void qian_show(node *p)
{
if(p)
{
printf("%c",p->ch);
qian_show(p->lc);
qian_show(p->rc);
}
}
void zhon_show(node *p)
{
if(p)
{
zhon_show(p->lc);
printf("%c",p->ch);
zhon_show(p->rc);
}
}
void hou_show(node *p)
{
if(p)
{
hou_show(p->lc);
hou_show(p->rc);
printf("%c",p->ch);
}
}
int main()
{
while(cin>>qianxu)
{
cin>>zhonxu;
node* r = NULL;
r = hou(0, strlen(qianxu)-1, 0, strlen(zhonxu)-1);
hou_show(r);
printf("\n");
}
return 0;
}
Hint
提示:
表示字符串的数据结构依然是字符数组。
总结:
KMP算法调用很简单,但难的是理解算法的思想。掌握算法的思想才能说是掌握算法。