您的位置:首页 > 其它

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: