树+栈+队列(表达式树)uva11234

题目的最关键部分是进行二叉树建树,  以及层次遍历逆序输出,还有利用栈的“括号匹配”思想。 二叉树的基本结构是,父结点都是操作符,子节点都是数字。 对于给出的序列, 从左到右遍历,遇到代表数字的小写则建立一个无儿子的树,然后把根结点指针入栈, 遇到代表操作符的大写字母,则从栈中弹出两个根结点,然后建立一个以大写字母为根,弹出的两个操作数为左右儿子的树,再把这个新树的根结点指针压入栈。如此循环下去。 最后,在栈顶的那个指针就是最后建成的树的根结点。  然后对这颗树进行层次遍历把字母取出来,最后逆序输出即可。

#include<iostream>
#include<cstdio>
#include<string>
#include<stack>
#include<queue>
using namespace std;
struct node
{
    char x;
    node *left,*right;
    node(char y,node *l,node *r):x(y),left(l),right(r){}
};
int n;
string a;
int main()
{
    #ifndef ONLINE_JUDGE
        freopen("in.txt","r",stdin);
    #endif

    cin>>n;
    while(n--)
    {
        cin>>a;
        stack<node*> st;
        queue<node*> q;
        for(int i=0;i<a.size();i++)
        {
            if(islower(a[i]))
                st.push(new node(a[i],NULL,NULL));
            else
            {
                node *x=st.top();st.pop();
                node *y=st.top();st.pop();
                st.push(new node(a[i],y,x));
            }
        }
        q.push(st.top());
        string ans;
        while(!q.empty())
        {
            node *tree=q.front();q.pop();
            ans+=tree->x;
            if(tree->left)q.push(tree->left);
            if(tree->right)q.push(tree->right);
        }
        for(int i=a.size()-1;i>=0;i--)cout<<ans[i];
        cout<<endl;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值