2016夏季练习——二叉树
2016-07-21 19:36
375 查看
来源:POJ1577
建树还是很简单的,但是这个题目的输入很值得玩味,可以说没有这样的输入,代码如此顺利是不可能的
代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAXN = 40;
char mp[MAXN][MAXN];
int cnt;
struct Tree{
int l,r;
char ch;
Tree():l(0),r(0){}
void ini(){
l=r=0;
}
};
Tree tree[MAXN];
int ptr;
void push(int rt,char data){
if(data<tree[rt].ch){
if(tree[rt].l==0){
tree[rt].l=ptr;
tree[ptr].ch=data;
tree[ptr].ini();
}
else push(tree[rt].l,data);
}
else{
if(tree[rt].r==0){
tree[rt].r=ptr;
tree[ptr].ch=data;
tree[ptr].ini();
}
else push(tree[rt].r,data);
}
}
void preorder(int rt){
printf("%c",tree[rt].ch);
if(tree[rt].l) preorder(tree[rt].l);
if(tree[rt].r) preorder(tree[rt].r);
}
int main(){
cnt=0;
while(scanf("%s",mp[cnt++])!=EOF){
if(mp[cnt-1][0]=='*'||mp[cnt-1][0]=='$'){
ptr=0;
for(int i=0;i<MAXN;++i) tree[i].ini();
tree[ptr].ch=mp[cnt-2][0];
for(int i=cnt-3;i>=0;i--){
int len = strlen(mp[i]);
for(int j=0;j<len;j++){
ptr++;
push(0,mp[i][j]);
}
}
preorder(0);
cout<<endl;
if(mp[cnt-1][0]=='$') break;
cnt=0;
}
}
return 0;
}
建树还是很简单的,但是这个题目的输入很值得玩味,可以说没有这样的输入,代码如此顺利是不可能的
代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAXN = 40;
char mp[MAXN][MAXN];
int cnt;
struct Tree{
int l,r;
char ch;
Tree():l(0),r(0){}
void ini(){
l=r=0;
}
};
Tree tree[MAXN];
int ptr;
void push(int rt,char data){
if(data<tree[rt].ch){
if(tree[rt].l==0){
tree[rt].l=ptr;
tree[ptr].ch=data;
tree[ptr].ini();
}
else push(tree[rt].l,data);
}
else{
if(tree[rt].r==0){
tree[rt].r=ptr;
tree[ptr].ch=data;
tree[ptr].ini();
}
else push(tree[rt].r,data);
}
}
void preorder(int rt){
printf("%c",tree[rt].ch);
if(tree[rt].l) preorder(tree[rt].l);
if(tree[rt].r) preorder(tree[rt].r);
}
int main(){
cnt=0;
while(scanf("%s",mp[cnt++])!=EOF){
if(mp[cnt-1][0]=='*'||mp[cnt-1][0]=='$'){
ptr=0;
for(int i=0;i<MAXN;++i) tree[i].ini();
tree[ptr].ch=mp[cnt-2][0];
for(int i=cnt-3;i>=0;i--){
int len = strlen(mp[i]);
for(int j=0;j<len;j++){
ptr++;
push(0,mp[i][j]);
}
}
preorder(0);
cout<<endl;
if(mp[cnt-1][0]=='$') break;
cnt=0;
}
}
return 0;
}
相关文章推荐
- 【离散数学】滨江学院 期末考试 题库
- WinForm上显示gif动画:转
- OpenStack glance 认证函数
- opencv读取摄像头数据
- [Leetcod]154. Find Minimum in Rotated Sorted Array II
- A - Can you find it?
- UVaOJ 10935 Throwing cards away I
- 【数据库原理】滨江学院姜青山 期末试卷知识点笔记整理 南京信息工程大学
- Winform 窗体最小化隐藏在桌面右下角:转
- 水题-HDU-5744-Keep On Movin
- 对象容器 ArrayList HashSet HashMap
- 阿里第一代 android dex加固的脱壳方法
- Java 多线程:volatile关键字
- 【操作系统】滨江学院 陈遥 期末试卷考点整理
- [www.infoshare.cc]Appium环境配置-Mac
- C#语音朗读文本 — TTS的实现
- hdu5734 Acperience(数学)
- UVa 10917 A Walk through the forest
- 7.21
- Android 支付宝API使用流程