zoukankan      html  css  js  c++  java
  • 表达式树

    #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;
    }
     
  • 相关阅读:
    arr.forEach()与for...in的用法举例
    git
    hql查询
    JAVA Hibernate工作原理及为什么要用
    mysql中key 、primary key 、unique key 与index区别
    aop
    hibernate json数据死循环
    nginx 转帖
    Maven搭建web项目
    ajaxfileupload 附加参数
  • 原文地址:https://www.cnblogs.com/tanhehe/p/2883508.html
Copyright © 2011-2022 走看看