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

来源:互联网 发布:淘宝店怎么样提高销量 编辑:程序博客网 时间:2024/06/05 18:01

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

想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 longusing 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;}


0 0
原创粉丝点击