您的位置:首页 > 其它

UVa-11234-Expressions

2014-09-17 11:42 423 查看
AOAPC
I: Beginning Algorithm Contests (Rujia Liu) :: Volume
2. Data Structures :: Lists



// 11234 - Expressions
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <stack>
#define MAXN 10000
using namespace std;
char prefix[MAXN];
int len;

typedef char elemtype;

typedef struct node
{
elemtype elem;
struct node* left;
struct node* right;
}*ptr;
ptr root;

ptr creatnode()
{
ptr t;
t = new node;
if(t == NULL)
exit(EXIT_FAILURE);
t->left = NULL;
t->right = NULL;
return t;
}

void bfs()
{
int front = 0;
int rear = 1;
ptr q[MAXN];
q[0] = root;
while(front < rear)
{
ptr t = q[front++];
prefix[len++] = t->elem;
if(t->left != NULL)
q[rear++] = t->left;
if(t->right != NULL)
q[rear++] = t->right;
}
}

void destroy(ptr p)
{
if(p == NULL)
return;
else
{
ptr x = p->left;
ptr y = p->right;
delete p;
destroy(x);
destroy(y);
}
}

int main(void)
{
stack<ptr> s;
ptr temp, x, y;

int i, c, t;
cin >> t;
getchar();
while(t--)
{
while(c = getchar(), c != '\n')
{
temp = creatnode();
temp->elem = c;
if(islower(c))
s.push(temp);
else
{
y = s.top();
s.pop();
x = s.top();
s.pop();
temp->left = x;
temp->right = y;
s.push(temp);
}
}

root = s.top();
s.pop();
len = 0;
bfs();

for(i = len-1; i >= 0; i--)
putchar(prefix[i]);
putchar('\n');

destroy(root);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: