表达式树

问题描述:《算法竞赛入门经典2 p353》
将一个表达式如(a+b*(c-d)-e/f)表示成一个二叉树。即给出中序序列求二叉树。
分析:
找出最后计算的运算符,它是整个树的根,然后递归处理;
找出最后计算的运算符:最后计算的运算符一定在括号外,并且当括号外有+-时一定为最右边一个+-运算符,如果没有+-,则一定是最右边的一个*/运算符。
代码:

#include <iostream>
#include <cstring>
#include <string>
#include <stdio.h>
#include <queue>
using namespace std;

const int maxn = 1000;
int lch[maxn],rch[maxn];
char op[maxn];
int nc=0;

int build_tree(char * s, int x, int y);
void print(int u);


int main()
{
    char s[1000];
    scanf("%s",s);
    int L=strlen(s);
    int u=build_tree(s,0,L);
    print(u);
    return 0;
}

int build_tree(char * s, int x, int y)
{
    int i,c1=-1,c2=-1,p=0,u;
    if(y-x==1)
    {
        u=++nc;
        lch[u]=0;
        rch[u]=0;
        op[u]=s[x];
        return u;
    }
    for(i=x;i<y;i++)
    {
        switch(s[i])
        {
            case '(':p++;break;
            case ')':p--;break;
            case '+':
            case '-':if(!p) c1=i;break;
            case '*':
            case '/':if(!p) c2=i;break;
            default : break;
        }
    }
    if(c1<0) c1=c2;
    if(c1<0) return build_tree(s,x+1,y-1);
    u=++nc;
    lch[u]=build_tree(s,x,c1);
    rch[u]=build_tree(s,c1+1,y);
    op[u]=s[c1];
    return u;
}

void print(int u)
{
    /*
    //先序序列
   cout<<op[u];
   if(lch[u]>0) print(lch[u]);
   if(rch[u]>0) print(rch[u]);
    */
    //层次遍历:
    queue<int> q;
    int t;
    while(!q.empty())
    {
        q.pop();
    }
    q.push(u);
    while(!q.empty())
    {
        t=q.front();
        q.pop();
        cout<<op[t];
        if(lch[t]>0)
            q.push(lch[t]);
        if(rch[t]>0)
            q.push(rch[t]);
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值