Open In App

Building Expression tree from Prefix Expression

Last Updated : 22 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a character array a[] represents 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++




//C++ code for the above approach
#include <iostream>
#include <cstring>
#include <cstdlib>
 
using namespace std;
 
// Represents a node of the required tree
struct node {
    char data;
    node *left, *right;
};
 
// Function to recursively build the expression tree
char* add(node** p, char* a)
{
 
    // If its the end of the expression
    if (*a == '\0')
        return '\0';
 
    while (1) {
        char* q = "null";
        if (*p == nullptr) {
 
            // Create a node with *a as the data and
            // both the children set to null
            node* nn = new node;
            nn->data = *a;
            nn->left = nullptr;
            nn->right = nullptr;
            *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 tree
void inr(node* p) // recursion
{
    if (p == nullptr) {
        return;
    }
    else {
        inr(p->left);
        cout << p->data << " ";
        inr(p->right);
    }
}
 
// Function to print the postfix expression for the tree
void postr(node* p)
{
    if (p == nullptr) {
        return;
    }
    else {
        postr(p->left);
        postr(p->right);
        cout << p->data << " ";
    }
}
 
int main()
{
    node* s = nullptr;
    char a[] = "*+ab-cd";
    add(&s, a);
    cout << "The Infix expression is:\n ";
    inr(s);
    cout << "\n";
    cout << "The Postfix expression is:\n ";
    postr(s);
    return 0;
}
//This code is contributed by Potta Lokesh


C




// C program to construct an expression tree
// from prefix expression
#include <stdio.h>
#include <stdlib.h>
 
// Represents a node of the required tree
typedef struct node {
    char data;
    struct node *left, *right;
} node;
 
// Function to recursively build the expression tree
char* 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 tree
void 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 tree
void postr(node* p)
{
    if (p == NULL) {
        return;
    }
    else {
        postr(p->left);
        postr(p->right);
        printf("%c ", p->data);
    }
}
 
// Driver code
int 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;
}


Java




import java.util.Stack;
 
// Represents a node of the required tree
class Node {
    char data;
    Node left, right;
 
    public Node(char item) {
        data = item;
        left = right = null;
    }
}
 
class ExpressionTree {
 
    static boolean isOperator(char c) {
        return c == '+' || c == '-' || c == '*' || c == '/';
    }
 
    static Node buildTree(String prefix) {
        Stack<Node> stack = new Stack<Node>();
 
        // Traverse the prefix expression in reverse order
        for (int i = prefix.length() - 1; i >= 0; i--) {
            char c = prefix.charAt(i);
 
            if (isOperator(c)) {
                Node left = stack.pop();
                Node right = stack.pop();
                Node node = new Node(c);
                node.left = left;
                node.right = right;
                stack.push(node);
            } else {
                Node node = new Node(c);
                stack.push(node);
            }
        }
 
        Node root = stack.peek();
        stack.pop();
 
        return root;
    }
 
    // Function to print the infix expression for the tree
    static void inOrder(Node node) {
        if (node != null) {
            inOrder(node.left);
            System.out.print(node.data + " ");
            inOrder(node.right);
        }
    }
 
    // Function to print the postfix expression for the tree
    static void postOrder(Node node) {
        if (node != null) {
            postOrder(node.left);
            postOrder(node.right);
            System.out.print(node.data + " ");
        }
    }
 
    public static void main(String[] args) {
        String prefix = "*+ab-cd";
        Node root = buildTree(prefix);
 
        System.out.println("Infix expression is:");
        inOrder(root);
 
        System.out.println("\nPostfix expression is:");
        postOrder(root);
    }
}


Python3




# Python3 program to construct an expression tree
# from prefix expression
 
# Represents a node of the required tree
class node:
    def __init__(self,c):
        self.data=c
        self.left=self.right=None
 
# Function to recursively build the expression tree
def 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 tree
def 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 tree
def postr(p):
 
    if (p == None):
        return
    else:
        postr(p.left)
        postr(p.right)
        print(p.data,end=' ')
 
# Driver code
if __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


C#




using System;
using System.Collections.Generic;
 
// Represents a node of the required tree
class Node
{
    public char data;
    public Node left, right;
 
    public Node(char item)
    {
        data = item;
        left = right = null;
    }
}
 
class ExpressionTree
{
    static bool IsOperator(char c)
    {
        return c == '+' || c == '-' || c == '*' || c == '/';
    }
 
    static Node BuildTree(string prefix)
    {
        Stack<Node> stack = new Stack<Node>();
 
        // Traverse the prefix expression in reverse order
        for (int i = prefix.Length - 1; i >= 0; i--)
        {
            char c = prefix[i];
 
            if (IsOperator(c))
            {
                Node left = stack.Pop();
                Node right = stack.Pop();
                Node node = new Node(c);
                node.left = left;
                node.right = right;
                stack.Push(node);
            }
            else
            {
                Node node = new Node(c);
                stack.Push(node);
            }
        }
 
        Node root = stack.Peek();
        stack.Pop();
 
        return root;
    }
 
    // Function to print the infix expression for the tree
    static void InOrder(Node node)
    {
        if (node != null)
        {
            InOrder(node.left);
            Console.Write(node.data + " ");
            InOrder(node.right);
        }
    }
 
    // Function to print the postfix expression for the tree
    static void PostOrder(Node node)
    {
        if (node != null)
        {
            PostOrder(node.left);
            PostOrder(node.right);
            Console.Write(node.data + " ");
        }
    }
 
    public static void Main(string[] args)
    {
        string prefix = "*+ab-cd";
        Node root = BuildTree(prefix);
 
        Console.WriteLine("Infix expression is:");
        InOrder(root);
 
        Console.WriteLine("\nPostfix expression is:");
        PostOrder(root);
    }
}


Javascript




// Javascript code to construct an expression tree
// from prefix expression
 
// Represents a node of the required tree
class Node {
constructor(c) {
this.data = c;
this.left = this.right = null;
}
}
 
// Function to recursively build the expression tree
function add(a) {
 
 
// If its the end of the expression
if (a === '') {
    return '';
}
 
// If the character is an operand
if (a.charCodeAt(0) >= 'a'.charCodeAt(0) && a.charCodeAt(0) <= 'z'.charCodeAt(0)) {
    return [new Node(a[0]), a.slice(1)];
} else {
 
    // Create a node with a[0] as the data and
    // both the children set to null
    let p = new Node(a[0]);
     
    // Build the left sub-tree
    let left = add(a.slice(1));
    p.left = left[0];
    let q = left[1];
     
    // Build the right sub-tree
    let right = add(q);
    p.right = right[0];
    q = right[1];
    return [p, q];
}
}
 
// Function to print the infix expression for the tree
function inr(p) { //recursion
 
if (p === null) {
    return;
} else {
    inr(p.left);
    console.log(p.data + ' ');
    inr(p.right);
}
}
 
// Function to print the postfix expression for the tree
function postr(p) {
 
 
if (p === null) {
    return;
} else {
    postr(p.left);
    postr(p.right);
    console.log(p.data + ' ');
}
}
 
// Driver code
 
let a = "*+ab-cd";
let sAndA = add(a);
let s = sAndA[0];
console.log("The Infix expression is:");
inr(s);
console.log("<br>")
console.log("The Postfix expression is:");
postr(s);


Output

The Infix expression is:
 a + b * c - d 
The Postfix expression is:
 a b + c d - * 

Time complexity: O(n)  because we are scanning all the characters in the given expression
Auxiliary space: O(1)



Similar Reads

Check if a triplet of buildings can be selected such that the third building is taller than the first building and smaller than the second building
Given an array arr[] consisting of N integers, where each array element represents the height of a building situated on the X co-ordinates, the task is to check if it is possible to select 3 buildings, such that the third selected building is taller than the first selected building and shorter than the second selected building. Examples: Input: arr
12 min read
Check if given inorder and preorder traversals are valid for any Binary Tree without building the tree
cGiven two arrays pre[] and in[] representing the preorder and inorder traversal of the binary tree, the task is to check if the given traversals are valid for any binary tree or not without building the tree. If it is possible, then print Yes. Otherwise, print No. Examples: Input: pre[] = {1, 2, 4, 5, 7, 3, 6, 8}, in[] = {4, 2, 5, 7, 1, 6, 8, 3}Ou
16 min read
Maximum sum increasing subsequence from a prefix and a given element after prefix is must
Given an array of n positive integers, write a program to find the maximum sum of increasing subsequence from prefix till ith index and also including a given kth element which is after i, i.e., k &gt; i. Examples : Input: arr[] = {1, 101, 2, 3, 100, 4, 5} i-th index = 4 (Element at 4th index is 100) K-th index = 6 (Element at 6th index is 5.) Outp
14 min read
Check if count of substrings in S with string S1 as prefix and S2 as suffix is equal to that with S2 as prefix and S1 as suffix
Given three strings S, S1, and S2, the task is to check if the number of substrings that start and end with S1 and S2 is equal to the number of substrings that start and end with S2 and S1 or not. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = "helloworldworldhelloworld", S1 = "hello", S2 = "world"Output: NoExpla
8 min read
Prefix Factorials of a Prefix Sum Array
Given an array arr[] consisting of N positive integers, the task is to find the prefix factorials of a prefix sum array of the given array i.e., [Tex]prefix[i] = (\sum_{0}^{i}arr[i])! [/Tex]. Examples: Input: arr[] = {1, 2, 3, 4}Output: 1 6 720 3628800Explanation:The prefix sum of the given array is {1, 3, 6, 10}. Therefore, prefix factorials of th
10 min read
Maximum prefix sum which is equal to suffix sum such that prefix and suffix do not overlap
Given an array arr[] of N Positive integers, the task is to find the largest prefix sum which is also the suffix sum and prefix and suffix do not overlap. Examples: Input: N = 5, arr = [1, 3, 2, 1, 4]Output: 4Explanation: consider prefix [1, 3] and suffix [4] which gives maximum prefix sum which is also suffix sum such that prefix and suffix do not
7 min read
Convert Infix expression to Postfix expression
Write a program to convert an Infix expression to Postfix form. Infix expression: The expression of the form "a operator b" (a + b) i.e., when an operator is in-between every pair of operands.Postfix expression: The expression of the form "a b operator" (ab+) i.e., When every pair of operands is followed by an operator. Examples: Input: A + B * C +
13 min read
Queries to find the Lower Bound of K from Prefix Sum Array with updates using Fenwick Tree
Given an array A[ ] consisting of non-negative integers and a matrix Q[ ][ ] consisting of queries of the following two types: (1, l, val): Update A[l] to A[l] + val.(2, K): Find the lower_bound of K in the prefix sum array of A[ ]. If the lower_bound does not exist, print -1. The task for each query of the second type is to print the index of the
14 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
Given a binary tree, the task is to print the maximum sum of nodes of a sub-tree which is also a Binary Search Tree.Examples: Input : 7 / \ 12 2 / \ \ 11 13 5 / / \ 2 1 38 Output:44 BST rooted under node 5 has the maximum sum 5 / \ 1 38 Input: 5 / \ 9 2 / \ 6 3 / \ 8 7 Output: 8 Here each leaf node represents a binary search tree also a BST with su
12 min read