无法从后缀表达式创建解析树

时间:2014-03-20 00:34:36

标签: c++ algorithm data-structures expression

我正在尝试从后缀表达式创建一个解析树。但它给了我分段错误。

这是我的代码:

#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;
}

1 个答案:

答案 0 :(得分:1)

修改所有

TREE *n;

TREE *n = new TREE;

因为它们似乎都是树上的新节点。您需要按operator new分配实际实例。