/*For given expression eg. a-b*c-d/e+f construct inorder sequence and traverse
it using postorder traversal(non recursive).*/
#include<iostream>
#include<string>
using namespace std;
typedef struct node
{
char cData;
class Cstack
struct node *pRt,*pLf;
}NODE;
{
NODE *pS[20];
void fPush(NODE* pPtr)
int iTop;
public:
Cstack()
{
iTop=-1;
}
{
pTmp=pS[iTop];
iTop++;
pS[iTop]=pPtr;
}
NODE* fPop()
{
NODE *pTmp;
return(pS[iTop]);
iTop--;
return(pTmp);
}
NODE* fTop()
{
}
int fIsempty()
{
string sExpr;
if(iTop==-1)
return 1;
return 0;
}
};
class Cexp
{
Cstack oS1,oS2;
void fDisplayPos(NODE*);
int iLen;
public:
void fGetExp();
int fPriority(char);
NODE* fBuildTree();
cout<<"Enter Expression : ";
void fDisplay(NODE*,int,NODE*);
};
void Cexp::fGetExp()
{
cin>>sExpr;
iLen=sExpr.size();
}
if(sExpr[i]!='*'&&sExpr[i]!='/'&&sExpr[i]!='+'&&sExpr[i]!='-')
NODE* Cexp::fBuildTree()
{
NODE *pNn,*pOpr,*pOp1,*pOp2;
for(int i=iLen-1;i>=0;i--)
{
{
pNn=new NODE;
if(!oS2.fIsempty()&&(fPriority((oS2.fTop())->cData)>fPriority(sExpr[i])))
pNn->cData=sExpr[i];
pNn->pLf=pNn->pRt=NULL;
oS1.fPush(pNn);
}
else
{
{
pOp1=oS1.fPop();
while( fPriority((oS2.fTop())->cData)>fPriority(sExpr[i]) )
{
pOpr=oS2.fPop();
pOp2=oS1.fPop();
pOpr->pRt=pOp1;
while(!oS2.fIsempty())
pOpr->pLf=pOp2;
oS1.fPush(pOpr);
}
}
pNn=new NODE;
pNn->cData=sExpr[i];
pNn->pRt=pNn->pLf=NULL;
oS2.fPush(pNn);
}
}
{
int Cexp::fPriority(char cCh)
pOpr=oS2.fPop();
pOp2=oS1.fPop();
pOp1=oS1.fPop();
pOpr->pRt=pOp1;
pOpr->pLf=pOp2;
oS1.fPush(pOpr);
}
return oS1.fTop();
}
{
if(cCh=='+'||cCh=='-')
oS2.fPush(pTmp);
return 1;
else
return 2;
}
void Cexp::fDisplayPos(NODE *pRoot)
{
Cstack oS1,oS2;
NODE *pTmp;
oS1.fPush(pRoot);
while(!oS1.fIsempty())
{
pTmp=oS1.fTop();
oS1.fPop();
if(pTmp->pLf)
void Cexp::fDisplay(NODE *ptr, int level,NODE *pRoot)
oS1.fPush(pTmp->pLf);
if(pTmp->pRt)
oS1.fPush(pTmp->pRt);
}
while(!oS2.fIsempty())
{
pTmp=oS2.fTop();
oS2.fPop();
cout<<pTmp->cData<<" ";
}
}
{
int i;
if (ptr != NULL)
{
fDisplay(ptr->pRt, level+1,pRoot);
pRoot=o.fBuildTree();
cout<<endl;
if (ptr == pRoot)
cout<<"Root->: ";
else
{
for (i = 0;i < level;i++)
cout<<" ";
}
cout<<ptr->cData;
fDisplay(ptr->pLf, level+1,pRoot);
}
}
int main()
{
NODE *pRoot;
Cexp o;
o.fGetExp();
o.fDisplay(pRoot,1,pRoot);
cout<<"\n";
o.fDisplayPos(pRoot);
cout<<"\n";
return 0;
}
No comments:
Post a Comment