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

Cannot create a parse tree from a postfix expression

本文关键字:创建 表达式 后缀      更新时间:2023-10-16

我试图从后缀表达式创建一个解析树。但是它给了我分割错误。

下面是我的代码:
#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分配实际实例