CSTFS1059 Reconstructing the Tree

本文介绍了一种根据先序和中序遍历序列重构二叉树的方法,并通过递归方式实现,最终输出后序遍历序列。文章提供了一个具体的C++实现案例。

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开了,马上上去水完几道题。还好确实比以前有进步。嗯嗯嗯!加油!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值