#Conversion from postfix expression to expression tree to prefix expression suing stack

2 messages · Page 1 of 1 (latest)

quaint jetty
#

Ive tried writing a code which takes in postfix expression as a string converts it into an expression tree through function pfxtoexpt and passes the expression tree returned to another function expttoprefix which is supposed to return the corr prefix expression
Im not getting any errors but im not able to get the prefix expression as output

Im attaching the screenshot of class node treenode and stack

string expttoprefix(TreeNode* root){
string prefixexp;
if (root!=NULL){
prefixexp+=root->value;
if (root->lt!=NULL)
{prefixexp+=expttoprefix(root->lt);}
if (root->rt!=NULL)
{prefixexp+=expttoprefix(root->rt);}
}
return prefixexp;
}

TreeNode* pfxtoexpt(const string& pfx){
Stack<TreeNode*> mystack;
const char* ptr=pfx.c_str();
while(ptr!=NULL){
if(isalnum(ptr)){
mystack.push(new TreeNode(ptr));
}
else{
TreeNode
rightop=mystack.getTop();
mystack.pop();
TreeNode
leftop= mystack.getTop();
mystack.pop();
TreeNode
opnode=new TreeNode(ptr);
mystack.pop();
opnode->lt=leftop;
opnode->rt=rightop;
mystack.push(opnode);}}
return mystack.getTop();
}
int main(){
string postfixexp;
cout<<"Enter the postfix expression:";
std::getline(cin,postfixexp);
TreeNode
expressiontree=pfxtoexpt(postfixexp);
cout<<"Prefix expression:"<<expttoprefix(expressiontree)<<endl;
return 0;
};

dense flintBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.