#include <stdio.h>
#include <conio.h>
typedef struct tn
{
char info;
struct tn *lchild;
struct tn *rchild;
}TreeNode, *Tree;
typedef struct node
{
Tree ptr;
struct node *link;
}Node,*Stack;
void InitStack(Stack *p);
void Push(Stack H,Tree x);
void Pop(Stack H);
Tree Top(Stack H);
int EmptyStack(Stack H);
Tree CreateTree(int x, Tree lchild, Tree rchild);/*to create one node of the tree*/
Tree ValueTree(char *expr);/*create the tree according the input*/
void PrintTree(Tree T);/*display the result((a+(b*c))+(((d*e)+f)*g))*/
void main()
{
char expression[]="abc*+de*f+g*+";
printf("The postfix is: abc*+de*f+g*+/n");
printf("After the change, the infix is:/n");
PrintTree(ValueTree(expression));
getch();
return;
}
void InitStack(Stack *p)
{
Stack q;
q =(Stack)malloc(sizeof(Node));
q->link=NULL;
q->ptr=NULL;
*p = q;
return;
}
void Push(Stack H,Tree x)
{
Stack q;
q =(Stack)malloc(sizeof(Node));
q->ptr=x;
q->link=H->link;
H->link=q;
return;
}
void Pop(Stack H)
{
Stack q;
q = H->link;
H->link=H->link->link;
free(q);
return;
}
Tree Top(Stack H)
{
return H->link->ptr;
}
int EmptyStack(Stack H)
{
if(H->link==NULL)
return 1;
else
return 0;
}
Tree CreateTree(int x, Tree lchild, Tree rchild)
{ Tree T;
T=(Tree)malloc(sizeof(TreeNode));
T->info=x;
T->lchild=lchild;
T->rchild=rchild;
return(T);
}
Tree ValueTree(char *expr)
{
Stack S;
Tree result;
Tree ch1,ch2;
InitStack(&S);
while(*expr!='/0')
{
if(*expr>='a'&& *expr<= 'z')
{ Push(S,CreateTree(*expr,NULL,NULL)); }
else
{
ch1=Top(S);Pop(S);
ch2=Top(S);Pop(S);
result=CreateTree(*expr,ch2,ch1);
Push(S,result);
}
expr++;
}
return(Top(S));
}
void PrintTree(Tree T)
{
if(T!=NULL)
{
if(T->lchild==NULL&&T->rchild==NULL)
printf("%c",T->info);
else
{
printf("(");
PrintTree(T->lchild);
printf("%c",T->info);
PrintTree(T->rchild);
printf(")");
}
}
}