DS – Code implementation from Postfix to Prefix:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node
{
            char c;
            struct node *left;
            struct node *right;      
};
struct node *stk[20], *temp, *root;
 
char postfix[20],ch;
int top=-1, max=20, len;
 
void preorder(struct node*);
void exptree();
void push(struct node*);
struct node* pop();
 
int main()
{
            printf(“Enter Postfix expression : “);
            scanf(“%s”, postfix);
           
            exptree();
           
            printf(“Prefix expression is : “);
            preorder(root);
            return 0;
}
 
void preorder(struct node *p)
{
            if(p != NULL)
            {
                        printf(“%c”, p->c);
                        preorder(p->left);
                        preorder(p->right);
                       
            }
}
 
void exptree()
{
            int i, j;
            i=0;
            j = strlen(postfix);
           
            while(i<j)
            {
                        switch(postfix[i])
                        {
                                    case ‘+’ :
                                    case ‘-‘ :
                                    case ‘*’ :
                                    case ‘/’ :
                                    case ‘%’ :          temp = (struct node*)malloc(sizeof(struct node));
                                                                        temp->c = postfix[i];
                                                                        temp->right = pop();
                                                                        temp->left = pop();
                                                                        push(temp);
                                                                        break;
                       
                                    default :           temp = (struct node*)malloc(sizeof(struct node));
                                                                        temp->c = postfix[i];
                                                                        temp->left = NULL;
                                                                        temp->right = NULL;
                                                                        push(temp);
                                                                        break;
                        }
                        ++i;
            }
            root = pop();
}
void push(struct node *p)
{
            if(top==max)
                        printf(“Stack is Full \n”);
            else
                        stk[++top] = p;
}
struct node* pop()
{
            if(top==-1)
                        printf(“Invalid expression \n”);
            else
                        return stk[top–];
}
Scroll to Top