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

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

    

#include<iostream>
#include<stack>
#include<string>
#include<cctype>
#include<stdio.h>
#define MAXN 10005
using 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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值