user6276841
user6276841

Reputation: 41

Using a stack to build an expression tree

I'm attempting to write an expression tree function that takes in a character array expression and outputs the prefix, infix and postfix version. I have written this code and it doesn't throw any errors, but when run the calculated values don't print out. I've tried to debug the function but still cannot come up with a solution. Is anyone able to give me any tips about what I'm doing wrong with this?

void Expression_Tree::build_expression_tree(char input[], int size)
{
    ETNode *temp, *t1, *t2;

    for (int i = 0; i < size; i++)
    {
        if(!(i == '+' || i == '-' || i == '*' || i == '/' || i == '^')) {
            temp = new ETNode;
            temp->left = temp->right = NULL;
            temp->input = i;

            tree_stack.push(temp);
        }
        else {
            temp = new ETNode;
            temp->left = temp->right = NULL;
            temp->input = i;

            t1 = tree_stack.top();
            tree_stack.pop();
            t2 = tree_stack.top();
            tree_stack.pop();

            temp->right = t1;
            temp->left = t2;

            tree_stack.push(temp);
        }
    }

    temp = tree_stack.top();
    tree_stack.pop();
}

I've just included the build_expression_tree function, if there is nothing deemed wrong with this then it mustn't be linking to my inorder, preorder and postorder functions properly. Thanks!

Upvotes: 0

Views: 828

Answers (1)

Gwen
Gwen

Reputation: 1452

It may be a copy-paste error, but you're using i as if it was a char.

I guess you want to use input[i] instead, at least in your if statement.

Upvotes: 2

Related Questions