Uva 11234 - Expressions//数据结构,二叉树

来源:互联网 发布:逆战领枪软件 编辑:程序博客网 时间:2024/05/16 18:34

     刚开始写题是有点想当然,自己感觉很简单。可是在写代码的时候才发现自己的建树方法很难实现。所以就在想有没有更简单的建树方法。联想到之前刷的括号匹配的题,灵感就来了。orz,这道题关键就在如何建树。下面是代码:

    

#include<iostream>#include<stack>#include<string>#include<cctype>#include<stdio.h>#define MAXN 10005using namespace std;struct node{    char val;    node* l;    node* r;};node* q[MAXN];char ans[MAXN];int n;void levelorder(node *root){    int front=0,rear=1;    q[0]=root;    n=0;    while(front<rear)    {        node* u=q[front++];        ans[n++]=u->val;        if(u->l==NULL&&u->r==NULL) continue;        if(u->l!=NULL) q[rear++]=u->l;        if(u->r!=NULL) q[rear++]=u->r;    }    return;}int main(){    int c;    //freopen("a.txt","r",stdin);    //freopen("b.txt","w",stdout);    cin>>c;    while(c--)    {        string str;        stack<node*> s;        cin>>str;        for(int i=0;i!=str.size();++i)        {            if(islower(str[i]))            {                node *p;                p=new node;                p->val=str[i];                p->l=p->r=NULL;                s.push(p);            }            if(isupper(str[i]))            {                node *p=s.top();                s.pop();                node *q=s.top();                s.pop();                node *root;                root=new node;                root->val=str[i];                root->l=q;                root->r=p;                s.push(root);            }        }        levelorder(s.top());        for(int i=n-1;i>=0;--i) cout<<ans[i];        cout<<endl;    }    //fclose(stdin);    //fclose(stdout);    return 0;}