我试图从postfix表达式创建一个解析树。但它给了我分割错误。
这是我的代码:

#include <iostream>
#include <stack>
#include <string>
#include <set>
#include <vector>
#include <cstdio>
#include <queue>
#include <list>
using namespace std;

struct my_tree{
    struct my_tree* left;
    char a;
    struct my_tree* right;
};

typedef struct my_tree TREE;


bool is_binary_op(char a){
    if(a == '|' || a == '.') return true;
    else return false;
}

bool is_unary_op(char a){
    if(a == '*') return true;
    else return false;
}

int main() {
    string postfix = "ab|*a.b.";
    stack<TREE*> parse_tree;
    for(unsigned i=0; i<postfix.length(); i++){
        if(is_binary_op(postfix[i])){
            TREE* n;

            TREE* right = parse_tree.top();
            parse_tree.pop();

            TREE* left = parse_tree.top();
            parse_tree.pop();

            n->left = left;
            n->a = postfix[i];
            n->right = right;

            parse_tree.push(n);
        } else if(is_unary_op(postfix[i])){
            TREE* n;

            TREE* left = parse_tree.top();
            parse_tree.pop();

            n->left = left;
            n->a = postfix[i];
            n->right = NULL;

            parse_tree.push(n);
        } else{
            TREE* n;

            n->left = NULL;
            n->a = postfix[i];
            n->right = NULL;
            parse_tree.push(n);
        }
    }
    return 0;
}

最佳答案

修改所有

TREE *n;

进入之内
TREE *n = new TREE;

因为它们看起来都是树上的一个新节点。您需要通过operator new分配实际实例。

07-24 18:36
查看更多