I am supposed to evaluate a postfix expression using an expression tree. Suppose I have a tree like this
-
/ \
+ *
/ \ / \
a b c d
I first need to evaluate a+b subtree and store its result in the + node, then c*d and so on untill i have the result in root node.
I tried the recursive approach using a stack, but that wasn't working. The pseudocode looked like this
- function eval(node)
- eval(node->left)
- eval(node->right)
- if(node is a leaf node) push it on the stack
- else if(node is an operand) pop a and pop b from stack node->value = a->value op b->value delete a b;
However this didn't work. I also have to show the tree on every step so as to show the nodes being reduced. I googled it many times but i was not able to find the required answer. Anyone please help me how to do this.
void expression_tree::evaluate(node *temp)
{
if(!temp)
return;
/// stack_postfix obj;
stack_postfix obj2;
evaluate(temp->left);
evaluate(temp->right);
if(temp->right == NULL && temp->left == NULL)
{
obj2.push(temp);
}
else
{
node * a = obj2.pop();
node *b = obj2.pop();
temp->value = a->value + b->value;
delete a;
delete b;
}
}
node::valuea field to store the evaluated value? if so what is the purpose of your stack? After all you already have the function call stack to use, and you don't need an explicit stack if you use recursion rather than loop. - Earth Engine