1 条题解

  • 0
    @ 2024-12-22 11:04:05

    C++ :

    #include <cstdio>
    #include <cstring>
    #include <stack>
    using namespace std;
    struct node{
        char v;
        struct node *l, *r;
        node(char c){
            v = c;
            l = r = NULL;
        }
    };
    stack<node*> p;                 // 操作数栈
    stack<char> q;                  // 操作符栈
    int len;
    char str[1010];
    
    /*
      将p栈顶两数与q栈顶一操作符构建一颗二叉树,并压入p栈
    */
    int getOrder(char c){
        switch(c){
        case '+': case '-':
            return 0;
        case '*': case '/':
            return 1;
        case '(': case ')':
            return 2;
        }
    }
    void buildNode(){
        node *t1 = new node(0);
        node *t2 = new node(0);
        char s;
    
        t2 = p.top(); p.pop();
        t1 = p.top(); p.pop();
        s = q.top(); q.pop();
    
        node *N = new node(s);
        N->l = t1;
        N->r = t2;
    
        p.push(N);
    }
    void PUSH(int &i){
        node *t = new node(str[i]);
        p.push(t);
    }
    /*
      根据中缀式构建表达式树
    */
    void buildTree(){
        int i;
        for(i = 0; i < len; i++){
            if(str[i] >= '0' && str[i] <= '9')
                PUSH(i);
            else if(str[i] == '(')
                q.push('(');
            else if(str[i] == ')'){
                while(q.top() != '(') buildNode();
                q.pop();
            }else{//+-*/
                while(!q.empty() && q.top()!='('
                   && getOrder(q.top()) >= getOrder(str[i]))
                    buildNode();
                q.push(str[i]);
            }
        }
        while(!q.empty()) buildNode();
    }
    void PRTraverse(node *t){
        if(t){
            printf("%c",t->v);
            PRTraverse(t->l);
            PRTraverse(t->r);
        }
    }
    void POTraverse(node *t){
        if(t){
            POTraverse(t->l);
            POTraverse(t->r);
            printf("%c", t->v);
        }
    }
    int main(){
        int k;
        scanf("%d", &k);
        while(k--){
            scanf("%s", str);
            len = strlen(str);
            buildTree();
            POTraverse(p.top());
            printf("\n");
            PRTraverse(p.top());
            printf("\n");
            p.pop();
        }
        return 0;
    }
    
    
    • 1

    信息

    ID
    358
    时间
    1000ms
    内存
    128MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者