uva 11234 Expressions(建立二叉树+层次遍历)

来源:互联网 发布:java的volatile 编辑:程序博客网 时间:2024/04/30 04:30

回学校两天了,算是做的第一道题吧,手有点生,看了别人的题解。。。

暑假期间就致力于刷题了,加油。。。

分析:题目的意思是让重排一下字母的顺序用队列的方式实现他们按照前面所述的出栈方式所实现的表达式,简单地说

就是建立一棵二叉树,然后对它层次遍历,之后逆序输出。

代码:

<span style="font-size:18px;">#include<stdio.h>#include<string.h>#include<stdlib.h>#include<stack>using namespace std;char a[10005];struct node{    char val;    node* l;    node* r;};char ans[10005];int sum;int bfs(node *root){    int front = 0;     int rear = 1;    sum=0;    node *q[10005];    q[0] = root;    while(front<rear)    {        node *u = q[front++];        ans[sum++] = u->val;        if(u->l!=NULL)          q[rear++] = u->l;        if(u->r!=NULL)          q[rear++] = u->r;    }    return 0;}int main(){    int T;    int i,j;    node* m,*n;    stack<node*>s;    scanf("%d",&T);        while(T--)    {        scanf("%s",a);        int len = strlen(a);        for(i=0; i<len; i++)        {            if(a[i]>='a'&&a[i]<='z')            {                node *p = new node;                p->val = a[i];                p->l = p->r = NULL;                s.push(p);            }             else            {                m=s.top();                s.pop();                n=s.top();                s.pop();                node *q = new node;                q->val = a[i];                q->l = n;                q->r = m;                s.push(q);            }        }        bfs(s.top());     for(i=sum-1; i>=0; i--)    printf("%c",ans[i]);    puts("");    }return 0;}</span>

0 0
原创粉丝点击