Blackbinary
Blackbinary

Reputation: 3986

Create a binary tree from a Stack?

I'm tasked with creating a program that turns something like ((X+3)*(X+4)) into a binary tree, along with some other features. So far, I have taken in the input, and parsed it into two stacks, one containing the operands, the other the operators.

I defined the stacks simply for now (so they only have a nextnode and char value. However, I seem to have problems adding values from the stacks into my tree (so probably a problem in defining the tree).

My stack is defined as such:

typedef struct node
{
    char value;
    struct node * nextnode;
} node;

My tree is defined:

typedef struct tree
{
    node * thisNode;
    struct tree *right, *left;
} tree;

I'm not sure about the node* part, perhaps it should be something different.

I've been considering the simple case of 2+3 for starters. In this case, the root of the tree should be +, with left being 2 and right being 3.

 +
/\
2 3

How to add something that's on a stack to my tree? I have tried using

root->thisNode = operatorTop;

Where operatorTop is the top of the operator stack (defined as node * operatorTop), but even that simple line seems to segfault.

Upvotes: 1

Views: 2175

Answers (1)

Hogan
Hogan

Reputation: 70523

Maybe the problem is you have not called malloc() to reserve the space for root.

(Compilers will report null pointer assignment, but segfault on null point dereference because you are pointing to a random place.)

Upvotes: 4

Related Questions