Stack - Infix expression tree

I'm trying to build a tree from an infix expression that will then print out the prefix and postfix versions using separate functions (I've already written these).

Is anyone able to tell me whether this code is even close to what I'm looking for and if so, why it doesn't print the desired output (or any output at all).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
void Expression_Tree::build_expression_tree(char input[], int size)
{
    ETNode *temp, *t1, *t2;

    for (int i = 0; i < size; i++)
    {
        if(!(input[i] == '+' || input[i] == '-' || input[i] == '*' || input[i] == '/' || input[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.empty()) ? NULL : (tree_stack.top());
            if(!tree_stack.empty()) 
            	tree_stack.pop();
            t2 = (tree_stack.empty()) ? NULL : (tree_stack.top());
            if(!tree_stack.empty())
            	tree_stack.pop();

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

            tree_stack.push(temp);
        }
    }

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


Thanks!
Line 10: Your're saving the index into the input, not the operator.
@AbstractionAnon thanks I missed that one, it unfortunately still doesn't output anything
unfortunately still doesn't output anything

Can't comment on that. There's no output logic in the code you posted.
@AbstractionAnon that's what I'm asking for help with.. I have functions to convert the tree to preorder and postorder, and this is my main file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include "Expression_Tree.h" 

int main()
{
	// Store parenthesized expression
	char input[] = {'2', '+', '(', '3', '*', '(', '2', '+', '2', ')', ')', '+', '5'};
	int size = sizeof(input)/sizeof(char);

	Expression_Tree a;
	a.build_expression_tree(input, size);

	cout << "Original input: ";
	for (int i = 0; i != sizeof(input)/sizeof(char); ++i) {
		cout << input[i];
	}
	cout << endl;

	cout << "Input in prefix notation: ";
	a.preorder();
	cout << endl;

	cout << "Input in infix notation: ";
	a.inorder();
	cout << endl;

	cout << "Input in postfix notation: ";
	a.postorder();
	cout << endl;

	return 0;
}
Last edited on
Topic archived. No new replies allowed.