Problem Address:http://cstfs.gdufs.edu.cn:8080/JudgeOnline/problem.jsp?id=1059
学校OJ上的一道题。
是对二叉树的重构。
题意是给出树的先序和中序遍历序列,要求树的后序遍历序列。
于是尝试建了一棵树。
在先序中按顺序读,然后把中序分为左右两边,递推式地处理下去。树建成之后按后序访问并输出同时释放节点空间。
代码如下:
#include <iostream>
using namespace std;
char pre[30],in[30];
struct node
{
char c;
node *left;
node *right;
};
node *search(int s, int e, int &index)
{
int j;
node *n;
if (s==e)
{
n = (node*)malloc(sizeof(node));
n->c = in[s];
n->left = NULL;
n->right = NULL;
return n;
}
else if (s<e)
{
n = (node*)malloc(sizeof(node));
for (j=s; in[j]!=pre[index] && j<=e; j++);
n->c = in[j];
if (s<=j-1)
{
index++;
n->left = search(s,j-1,index);
}
else
{
n->left = NULL;
}
if (j+1<=e)
{
index++;
n->right = search(j+1,e,index);
}
else
{
n->right = NULL;
}
return n;
}
return NULL;
}
void show(node *a)
{
if (a==NULL) return;
show(a->left);
show(a->right);
printf("%c", a->c);
free(a);
}
int main()
{
node *root;
int i,index;
while(scanf("%s", pre)!=EOF)
{
scanf("%s", in);
for (i=0; pre[i]!='/0'; i++);
index = 0;
root = search(0, i-1, index);
show(root);
printf("/n");
}
return 0;
}
p.s.学校的OJ开了,马上上去水完几道题。还好确实比以前有进步。嗯嗯嗯!加油!
本文介绍了一种根据先序和中序遍历序列重构二叉树的方法,并通过递归方式实现,最终输出后序遍历序列。文章提供了一个具体的C++实现案例。
1545

被折叠的 条评论
为什么被折叠?



