NYOJ 756 重建二叉树
来源:互联网 发布:程序员 bug 编辑:程序博客网 时间:2024/05/17 04:12
重建二叉树
时间限制:1000 ms | 内存限制:65535 KB
难度:3
- 描述
- 题目很简单,给你一棵二叉树的后序和中序序列,求出它的前序序列(So easy!)。
- 输入
- 输入有多组数据(少于100组),以文件结尾结束。
每组数据仅一行,包括两个字符串,中间用空格隔开,分别表示二叉树的后序和中序序列(字符串长度小于26,输入数据保证合法)。 - 输出
- 每组输出数据单独占一行,输出对应得先序序列。
- 样例输入
ACBFGED ABCDEFGCDAB CBAD
- 样例输出
DBACEGFBCAD
这道题目是我大一下学期刚刚做过的课程设计 当时是在百度上copy的,今天刷题的时候看到了这一题,又把之前的课程设计找出来看了一下,写了一遍,发现那次的课程设计不难,只是我没有耐心去搞懂他。构建二叉树的是递归的思想,比较容易犯错的是在计算左子树和右子树范围的时候比较麻烦,
#include<stdio.h>#include<malloc.h>#include <string.h>#define ElemType chartypedef struct BiTree{ElemType data;struct BiTree *lchild,*rchild;}BiTree,*BiNode;char pre[100];char in[100];char post[100];void createBiTree(BiNode &T,int last,int infirst,int lengh){if(lengh<=0){T=NULL;}else{T=(BiNode)malloc(sizeof(BiTree));T->data=post[last];int min=strchr(in,post[last])-in;int lenf=min-infirst;createBiTree(T->lchild,last-(lengh-1-lenf)-1,infirst,lenf);int lenr=lengh-1-lenf;createBiTree(T->rchild,last-1,min+1,lenr);}}void preoder(BiNode T){if(T!=NULL){printf("%c",T->data);preoder(T->lchild);preoder(T->rchild);}}int main(){BiNode T;while(scanf("%s %s",post,in)!=EOF){createBiTree(T,strlen(post)-1,0,strlen(in)); preoder(T); printf("\n");}return 0;}
我在acm的讨论区看到了一个很简短的算法,看了之后我真的很佩服,他熟练的运用了前中后序遍历的性质,在数组的基础上直接就能递归求出前序遍历。(因为二叉树的构建一般都是按先序遍历)甚是佩服,也自知惭愧。需要努力的还有很多 先把数据结构的基础给打好才行。
#include<string.h>#include<stdio.h>char a[30]={},b[30]={};void xian(int l1,int r1,int l2,int r2){if(l1>r1)return;int s=0;while(a[r1]!=b[l2+s])s++;printf("%c",a[r1]);xian(l1,l1+s-1,l2,l2+s-1);xian(l1+s,r1-1,l2+s+1,r2);}int main(){while(scanf("%s %s",a,b)!=EOF){int len;len=strlen(a);xian(0,len-1,0,len-1);printf("\n");}return 0;}
阅读全文
0 0
- NYOJ-756重建二叉树
- nyoj-756-重建二叉树
- nyoj-756 重建二叉树
- NYOJ 756 重建二叉树
- NYOJ 756 重建二叉树
- NYOJ--重建二叉树
- NYOJ 题目756 重建二叉树
- nyoj 756 重建二叉树(总结)
- nyoj 1063 - 生活的烦恼 二叉树重建及遍历
- NYOJ 756 重建二叉树【由二叉树的后序和中序建立二叉树并得先序】
- nyist oj 756 重建二叉树
- 南阳 oj 重建二叉树 题目756
- 3.9重建二叉树
- 重建二叉树
- 二叉树重建
- 二叉树重建
- 二叉树的重建
- 重建二叉树
- 如何在myeclipse中新建web project
- 2017年八月1号到6号
- 更改easyui中Accordion(分类)的背景
- 3745: [Coci2015]Norma
- [Android Studio系列(五)] Android Studio手动配置Gradle的方法
- NYOJ 756 重建二叉树
- 【mysql】insert的几种方式
- com.google.gson.JsonSyntaxException的解决方法
- android-clipChildren属性
- 解决antd Cannot read property 'validate' of undefined
- mysql 5.19 windows安装后无法启动服务
- Leetcode挑战题——2 Keys Keyboard
- STM32F103系列 PB4引脚问题
- CSRF攻击防御---验证HTTP Referer