Building Expression tree from Prefix Expression - GeeksforGeeks

03 Nov, 2021
Given a character array a[] representing a prefix expression. The task is to build an Expression Tree for the expression and then print the infix and postfix expression of the built tree.Examples:  
Input: a[] = “*+ab-cd” Output: The Infix expression is: a + b * c – d The Postfix expression is: a b + c d – *Input: a[] = “+ab” Output: The Infix expression is: a + b The Postfix expression is: a b +  
 
Approach: If the character is an operand i.e. X then it’ll be the leaf node of the required tree as all the operands are at the leaf in an expression tree. Else if the character is an operator and of the form OP X Y then it’ll be an internal node with left child as the expressionTree(X) and right child as the expressionTree(Y) which can be solved using a recursive function.Below is the implementation of the above approach: 
C
Python3
// C program to construct an expression tree// from prefix expression#include <stdio.h>#include <stdlib.h> // Represents a node of the required treetypedef struct node {    char data;    struct node *left, *right;} node; // Function to recursively build the expression treechar* add(node** p, char* a){     // If its the end of the expression    if (*a == '\0')        return '\0';     while (1) {        char* q = "null";        if (*p == NULL) {             // Create a node with *a as the data and            // both the children set to null            node* nn = (node*)malloc(sizeof(node));            nn->data = *a;            nn->left = NULL;            nn->right = NULL;            *p = nn;        }        else {             // If the character is an operand            if (*a >= 'a' && *a <= 'z') {                return a;            }             // Build the left sub-tree            q = add(&(*p)->left, a + 1);             // Build the right sub-tree            q = add(&(*p)->right, q + 1);             return q;        }    }} // Function to print the infix expression for the treevoid inr(node* p) // recursion{    if (p == NULL) {        return;    }    else {        inr(p->left);        printf("%c ", p->data);        inr(p->right);    }} // Function to print the postfix expression for the treevoid postr(node* p){    if (p == NULL) {        return;    }    else {        postr(p->left);        postr(p->right);        printf("%c ", p->data);    }} // Driver codeint main(){    node* s = NULL;    char a[] = "*+ab-cd";    add(&s, a);    printf("The Infix expression is:\n ");    inr(s);    printf("\n");    printf("The Postfix expression is:\n ");    postr(s);    return 0;}
# Python3 program to construct an expression tree# from prefix expression # Represents a node of the required treeclass node:    def __init__(self,c):        self.data=c        self.left=self.right=None # Function to recursively build the expression treedef add(a):     # If its the end of the expression    if (a == ''):        return ''     # If the character is an operand    if a[0]>='a' and a[0]<='z':        return node(a[0]),a[1:]    else:        # Create a node with a[0] as the data and        # both the children set to null        p=node(a[0])        # Build the left sub-tree        p.left,q=add(a[1:])        # Build the right sub-tree        p.right,q=add(q)        return p,q          # Function to print the infix expression for the treedef inr(p): #recursion     if (p == None):        return    else:        inr(p.left)        print(p.data,end=' ')        inr(p.right) # Function to print the postfix expression for the treedef postr(p):     if (p == None):        return    else:        postr(p.left)        postr(p.right)        print(p.data,end=' ') # Driver codeif __name__ == '__main__':         a = "*+ab-cd"    s,a=add(a)    print("The Infix expression is:")    inr(s)    print()    print("The Postfix expression is:")    postr(s) # This code is contributed by Amartya Ghosh
The Infix expression is:
 a + b * c - d 
The Postfix expression is:
 a b + c d - *
 
amartyaghoshgfg
expression-evaluation
C Programs
Data Structures
Tree
Data Structures
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Regular expressions in C
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Doubly Linked List | Set 1 (Introduction and Insertion)
Implementing a Linked List in Java using Class