nyoj756 重建二叉树

来源:互联网 发布:淘宝双十一消费者规则 编辑:程序博客网 时间:2024/04/27 22:41

重建二叉树

时间限制:1000 ms  |  内存限制:65535 KB
难度:3
描述
题目很简单,给你一棵二叉树的后序和中序序列,求出它的前序序列(So easy!)。
输入
输入有多组数据(少于100组),以文件结尾结束。
每组数据仅一行,包括两个字符串,中间用空格隔开,分别表示二叉树的后序和中序序列(字符串长度小于26,输入数据保证合法)。
输出
每组输出数据单独占一行,输出对应得先序序列。
样例输入
ACBFGED ABCDEFGCDAB CBAD
样例输出
DBACEGFBCAD

思路:看到本题首先想到的是重建一个二叉树,由中序遍历和后序遍历可以重新构建一颗二叉树,然后先序遍历输出求的结果

代码如下:

#include<stdio.h>#include<stdlib.h>#include<string.h>typedef struct node{char num;struct node *lchild,*rchild;}NODE,*PNODE;void buildTree(PNODE * root,char*post,char*in,int len)/*root表示根节点,post表示后序遍历的结果,in表示中序遍历的结果,len表示当前子树的长度*/ {if(len==0){*root=NULL;     return;}PNODE node=(PNODE)malloc(sizeof(NODE));node->num=post[len-1];node->lchild=node->rchild=NULL;*root=node;char *s=strchr(in,node->num);//找到根节点在中序遍历中的位置 int leftlen=strlen(in)-strlen(s);//左子树的长度 int rightlen=len-leftlen-1;//右子树的长度 buildTree(&(*root)->lchild,post,in,leftlen);//递归建左子树 buildTree(&(*root)->rchild,post+leftlen,s+1,rightlen);//递归建立右子树 }void bianliTree(PNODE root)//先序遍历 {if(root==NULL)return ;printf("%c",root->num);    bianliTree(root->lchild);bianliTree(root->rchild);}int main(){char post[26],in[26];    while(scanf("%s %s",post,in)!=EOF){PNODE root=NULL;buildTree(&root,post,in,strlen(in));bianliTree(root);printf("\n");}return  0;}

AC过后看到大神的代码瞬间泪奔太简单了根本不用重建二叉树,只需要每次把求得的结果输出即可!

大神代码:

#include<stdio.h>#include<string.h>void ReBuild(char *pre, char *in,char *post, int len){if(len>0){int n =strchr(in,post[len-1])-in;ReBuild(pre+1,in,post,n);ReBuild(pre+n+1,in+n+1,post+n,len-n-1);pre[0]=post[len-1];}}int main(){char pre[30],in[30],post[30];int len;while(~scanf("%s%s",post,in)){len=strlen(post);ReBuild(pre,in,post,len);pre[len]=0;puts(pre);}}


0 0