2016夏季练习——二叉树

来源:互联网 发布:java单例类 编辑:程序博客网 时间:2024/05/30 04:58

来源: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;}


1 0