Tree Grafting,树转换成二叉树,tree recovery,遍历顺序确定二叉树
来源:互联网 发布:python库中文 编辑:程序博客网 时间:2024/05/29 08:18
把树转换成二叉树很简单,
深度搜索这棵树,递归创建每一个子节点;再把第一个子节点变成左子树,其他子节点变成第一个子节点右子树。
这道题比较水只要求求高度,模拟一遍即可
#include<cstdio>#include<iostream>#include<cstring>#define mem(x) memset(x,0,sizeof(x))using namespace std;const int N=1e4+1;const int INF=0x7fffffff;int layer[N];//layer存放当前顺序树每一层的最大高度。int h1,h2,mh1,mh2;//h1是当前顺序树高度,h2是当前二叉树高度,mh1是顺序树的最大高度,mh2void init(){ mem(layer); mh1=mh2=h1=h2=0;}int main(){ //freopen("in.txt","r",stdin); char c,pre; int kase=0; pre='\0'; while((c=getchar())!='#'){ ++kase; init(); while(c!='\n'){ ,,,同时更新mh2 if(c=='d'){ pre=c;//d到下一层并加一个结点h2++ h2++;mh2=max(mh2,h2);//更新mh2 if(pre=='d'){ //连续d,h1++,layer[h1]++; h1++;mh1=max(mh1,h1); //更新mh1 } layer[h1]=h2; } else{ h2=layer[h1];h1--;//u到上一层,h2更新为layer[h1],h1--; } //printf("h1=%d,h2=%d,mh1=%d,mh2=%d\n",h1,h2,mh1,mh2); c=getchar(); } printf("Tree %d: %d => %d\n",kase,mh1,mh2); } return 0;}
中序和 先序后序的其中一种就可以唯一确定一颗二叉树;
递归建树,递归遍历的代码如下
#include<cstdio>#include<cstdlib>#include<iostream>#include<cstring>using namespace std;struct node{ node *l,*r; char c;};char pre[28],in[29];node *biuld(int l1,int r1,int l2,int r2){ if(l1>r1) return NULL; node * root=(node *)malloc(sizeof(node)); root->c=pre[l1]; root->l=NULL; root->r=NULL; for(int i=l2;i<=r2;i++){ if(in[i]==root->c){ root->l=biuld(l1+1,l1+i-l2,l2,i-1); root->r=biuld(l1+i-l2+1,r1,i+1,r2); break; } } return root;}void post_order(node *root){ if(root!=NULL){ post_order(root->l); post_order(root->r); printf("%c",root->c); }}int main(){ while(~scanf("%s%s",pre+1,in+1)){ int len=strlen(pre+1); post_order(biuld(1,len,1,len));cout<<endl; } return 0;}
阅读全文
0 0
- Tree Grafting,树转换成二叉树,tree recovery,遍历顺序确定二叉树
- Tree Recovery(过遍历确定二叉树结构)
- POJ 3437 Tree Grafting 多叉树转二叉树
- POJ 3437 Tree Grafting(二叉树高度)
- poj 2255 Tree Recovery (二叉树的顺序遍历)
- 二叉树(Tree Recovery)
- POJ 2255 Tree Recovery 二叉树遍历
- poj2255 Tree Recovery 二叉树遍历
- 536 - Tree Recovery(二叉树遍历)
- POJ2255 Tree Recovery 二叉树遍历
- POJ 2255 Tree Recovery (二叉树遍历)
- uva536-Tree Recovery-二叉树遍历
- POJ2255 Tree Recovery(二叉树遍历)
- (二叉树递归)A - Tree Grafting(9.1.1)
- POJ 2255 Tree Recovery 二叉树的遍历
- POJ 2255 Tree Recovery 二叉树+遍历+递归
- poj 2255 Tree Recovery(求后序遍历,二叉树)
- poj 2255 Tree Recovery(二叉树的遍历)
- JMeter基础之一 一个简单的性能测试
- javascript递归创建导航菜单
- Android测试思路
- Hadoop技术
- JVisualVM 远程连接 JMX 和 jstatd
- Tree Grafting,树转换成二叉树,tree recovery,遍历顺序确定二叉树
- fastjson使用技巧整理
- poj 2155 Matrix(树状数组)
- hive weekofyear 怪异的姿势
- hdu1521-dp
- java基础之一 对象,接口
- 工厂方法模式
- C++ 单生产者多消费者多线程示例
- tcp超时重传