表达式树

#include <stdio.h>
#include <string.h>

#define maxn 1000
//const int maxn = 1000;

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

int build_tree(char *s, int x, int y){
    int i, c1 = -1, c2 = -1, p = 0;
    int u;
    if(y-x == 1){
        u = ++nc;
        lch[u] = 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;
        }

    }
    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){  //后序输出
    if(u != 0){
        print(lch[u]);
        print(rch[u]);
        printf("%c", op[u]);
    }

}

int main(){
    char s[] = "a+b*(c-d)-e/f";
    build_tree(s, 0, strlen(s));
    print(1); putchar('\n');
    int i;
    for(i=0; i<20; i++){
        printf("u:%d lch:%d rch%d op %c\n", i, lch[i], rch[i], op[i]);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值