码迷,mamicode.com
首页 > 其他好文 > 详细

南阳OJ-756 重建二叉树(二叉树的中序遍历和后序遍历求先序遍历)

时间:2016-05-10 20:46:46      阅读:599      评论:0      收藏:0      [点我收藏+]

标签:

重建二叉树

时间限制:1000 ms  |  内存限制:65535 KB
难度:3
 
描述
题目很简单,给你一棵二叉树的后序和中序序列,求出它的前序序列(So easy!)。
 
输入
输入有多组数据(少于100组),以文件结尾结束。
每组数据仅一行,包括两个字符串,中间用空格隔开,分别表示二叉树的后序和中序序列(字符串长度小于26,输入数据保证合法)。
输出
每组输出数据单独占一行,输出对应得先序序列。
样例输入
ACBFGED ABCDEFG
CDAB CBAD
样例输出
DBACEGF
BCAD
二叉树递归遍历
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
/*前序遍历:根节点->左子树->右子树
中序遍历:左子树->根节点->右子树
后序遍历:左子树->右子树->根节点*/
struct node {
  char value;
  node *lchild, *rchild;
};
node *newnode(char c) {//创建新的结点 
  node *p = (node*)malloc(sizeof(node));
  (*p).value = c;
  (*p).lchild = (*p).rchild = NULL;
}
node *rebuild(char* post, char* in, int n) {//由后序遍历和中序遍历重建二叉树 
  if (n == 0) return NULL;
  char ch = post[n-1];//后序遍历最后一个结点即为根结点
  node *p = newnode(ch);//创建子树的根节点 
  int i = 0;
  while (i < n && in[i] != ch) i++;//根据中序遍历得到左子树与右子树的分界
  int l_len = i;
  int r_len = n-i-1;
  if (l_len > 0) (*p).lchild = rebuild(post, in, l_len);//递归遍历左子树 
  if (r_len > 0) (*p).rchild = rebuild(post+l_len, in+l_len+1, r_len);//递归遍历右子树 
  return p;
}
void preorder(node *p) {//先序遍历二叉树 ,打印各个结点的权值 
  if (p == NULL) return;
  printf("%c", (*p).value);
  preorder((*p).lchild);
  preorder((*p).rchild);
}
int main() {
  char in[30], post[30];
  while (scanf("%s%s", post, in) != EOF) {
    node *root = rebuild(post, in, strlen(post));
    preorder(root);
    printf("\n");
  }
} 

 

南阳OJ-756 重建二叉树(二叉树的中序遍历和后序遍历求先序遍历)

标签:

原文地址:http://www.cnblogs.com/Rhett-Q/p/5479140.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!