UVA表达式树的后序遍历和层次遍历和建树

本文详细介绍了如何通过解析后缀表达式建立表达式树,并利用层次遍历方法反转输出结果的过程。重点在于理解表达式树的构建逻辑及其在不同场景下的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

太笨又太蠢,做的小白书后面的题,前面写的线性表部分的内容,就一直在想线性表的做法,

想vector,想stack,结果是表达式树,建立二叉树根据后缀表达式,然后层次遍历一遍反转就行了。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<string>
#include<cctype>
#include<cmath>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<stack>
#include<ctime>
#include<algorithm>
#include<sstream>
#define LL long long
using namespace std;
const int maxn=1e4+5;
int main()
{
    int t;
    cin>>t;
    getchar();
    while(t--)
    {
        string s;
        getline(cin,s);
        string re="";
        stack<int> v;
        int left[maxn],right[maxn];
        for(int i=0;i<s.length();i++)
        {
            if(islower(s[i]))
            {
                v.push(i);
                left[i]=right[i]=-1;
            }
            else
            {
                int rr=v.top();
                v.pop();
                int ll=v.top();
                v.pop();
                v.push(i);
                left[i]=ll;
                right[i]=rr;
            }
        }
        queue<int> q;
        q.push(v.top());
        while(!q.empty())
        {
            int ai=q.front();
            q.pop();
            re=s[ai]+re;
            if(left[ai]!=-1) q.push(left[ai]);
            if(right[ai]!=-1) q.push(right[ai]);
        }
        cout<<re<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值