这题的思路是首先要建立 表达式树,基本结构是父结点都是操作符,根节点都是数字。
对于给出的序列, 从左到右遍历,遇到代表数字的小写则建立一个无儿子的树,然后把根结点指针入栈, 遇到代表操作符的大写字母,则从栈中弹出两个根结点,然后建立一个以大写字母为根,弹出的两个操作数为左右儿子的树,再把这个新树的根结点指针压入栈。如此循环下去。 最后,在栈顶的那个指针就是最后建成的树的根结点。 然后对这颗树进行层次遍历把字母取出来,最后逆序输出即可。
这都是网上给的思路,自己刚拿到这题是不会的,,至于为会这样做不太清楚,,求指导!
一个是用数组:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <set>
#include <stack>
#include <queue>
using namespace std;
#define N 10010
#define Dbag printf("haha\n");
int L[N], R[N];
struct node
{
char v;
int l, r;
}tree[N];
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
stack<int> s;
char ptr[N];
scanf("%s", ptr);
int len = strlen(ptr);
for(int i = 0; i < len; i++)
{
if(islower(ptr[i]))
{
tree[i].v = ptr[i];
tree[i].l = -1;
tree[i].r = -1;
s.push(i);
}
else
{
int r = s.top(); s.pop();
int l = s.top(); s.pop();
tree[i].v = ptr[i];
tree[i].l = l; tree[i].r = r;
s.push(i);
}
}
queue <int> qe;
int root = s.top();
qe.push(root);
char ans[N]; int cnt = 0;
while(!qe.empty())
{
int pos = qe.front();
qe.pop();
ans[cnt++] = tree[pos].v;
if(tree[pos].l!=-1)
qe.push(tree[pos].l);
if(tree[pos].r!=-1)
qe.push(tree[pos].r);
}
for(int i = cnt-1; i >= 0; i--)
printf("%c", ans[i]);
printf("\n");
}
return 0;
}
指针版本:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <set>
#include <stack>
#include <queue>
using namespace std;
#define N 100000
#define Dbag printf("haha\n");
struct node
{
char v;
node *l, *r;
};
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
stack <node*> s;
char ptr[N];
scanf("%s",ptr); int len = strlen(ptr);
for(int i = 0; i < len; i++)
{
if(islower(ptr[i]))
{
node *tmp = new node;
tmp->l=NULL; tmp->r=NULL;
tmp->v = ptr[i];
s.push(tmp);
}
else
{
node *tmp1 = s.top(); s.pop();
node *tmp2 = s.top(); s.pop();
node *tmp = new node;
tmp->l = tmp2; tmp->r = tmp1;
tmp->v = ptr[i];
s.push(tmp);
}
}
char ans[N];int cnt = 0;
queue <node*> qe;
node *root = s.top();
qe.push(root);
while(!qe.empty())
{
node *pos = qe.front();
qe.pop();
ans[cnt++] = pos->v;
if(pos->l!=NULL)
qe.push(pos->l);
if(pos->r!=NULL)
qe.push(pos->r);
}
for(int i = cnt-1; i >= 0; i--)
printf("%c", ans[i]);
printf("\n");
}
return 0;
}