سؤال

I am trying to create a parse tree from a postfix expression. But it is giving me segmentation error.

Here is my code:

#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;
}
هل كانت مفيدة؟

المحلول

Modify all the

TREE *n;

into

TREE *n = new TREE;

since all of them seems to be a new node on tree. You need to allocate the actual instance by operator new.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top