题目链接:http://acm.hit.edu.cn/hoj/problem/view?id=1452
题意:已知中序表达式和先序表达式求后序表达式。
我们知道先序、中序、后序、层序这四种遍历方式中,只要有中序和其他任意一种顺序,即可构建这个二叉树。并且求得其他的顺序。
方法一:一步到位
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <algorithm>
using namespace std;
char pre[30];
char in[30];
void findPost(int root,int left,int right)
{
if(left>right)
return;
int i;
//left,right是针对于中缀表达式的
for(i = left;i<=right;i++)
{
if(in[i] == pre[root])
{
break;
}
}
//in[i]是根节点
findPost(root+1,left,i-1);
findPost(root + 1 + i - left,i+1,right);
printf("%c",in[i]);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
while(scanf(" %s %s",pre,in)!=EOF)
{
findPost(0,0,strlen(in)-1);
printf("\n");
}
}
方法二:构建好二叉树后,再后序遍历。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <algorithm>
using namespace std;
char pre[30];
char in[30];
struct Tree
{
Tree * lch;
Tree * rch;
char data;
};
//注意root要取地址。
void build_tree(Tree * &root,int index,int left,int right)
{
if(left>right)
return;
if(root == NULL)
{
root = new Tree;
root->rch = NULL;
root->lch = NULL;
root->data = pre[index];
}
int i;
for(i = left;i<=right;i++)
{
if(pre[index] == in[i])
{
break;
}
}
build_tree(root->lch,index + 1,left,i-1);
build_tree(root->rch,index + 1 + i - left,i+1,right);
}
void findPost(Tree * root)
{
if(root == NULL)
return;
findPost(root->lch);
findPost(root->rch);
printf("%c",root->data);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
while(scanf(" %s %s",pre,in)!=EOF)
{
Tree * root = NULL;
build_tree(root,0,0,strlen(in)-1);
findPost(root);
printf("\n");
}
}