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++
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
struct node {
char data;
node *left, *right;
};
char* add(node** p, char* a)
{
if (*a == '\0')
return '\0';
while (1) {
char* q = "null";
if (*p == nullptr) {
node* nn = new node;
nn->data = *a;
nn->left = nullptr;
nn->right = nullptr;
*p = nn;
}
else {
if (*a >= 'a' && *a <= 'z') {
return a;
}
q = add(&(*p)->left, a + 1);
q = add(&(*p)->right, q + 1);
return q;
}
}
}
void inr(node* p)
{
if (p == nullptr) {
return;
}
else {
inr(p->left);
cout << p->data << " ";
inr(p->right);
}
}
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;
}
|
C
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char data;
struct node *left, *right;
} node;
char* add(node** p, char* a)
{
if (*a == '\0')
return '\0';
while (1) {
char* q = "null";
if (*p == NULL) {
node* nn = (node*)malloc(sizeof(node));
nn->data = *a;
nn->left = NULL;
nn->right = NULL;
*p = nn;
}
else {
if (*a >= 'a' && *a <= 'z') {
return a;
}
q = add(&(*p)->left, a + 1);
q = add(&(*p)->right, q + 1);
return q;
}
}
}
void inr(node* p)
{
if (p == NULL) {
return;
}
else {
inr(p->left);
printf("%c ", p->data);
inr(p->right);
}
}
void postr(node* p)
{
if (p == NULL) {
return;
}
else {
postr(p->left);
postr(p->right);
printf("%c ", p->data);
}
}
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;
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 postfix)
{
Stack<Node> stack = new Stack<Node>();
for (int i = 0; i < postfix.length(); i++) {
char c = postfix.charAt(i);
if (isOperator(c)) {
Node right = stack.pop();
Node left = 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;
}
static void inOrder(Node node)
{
if (node != null) {
inOrder(node.left);
System.out.print(node.data + " ");
inOrder(node.right);
}
}
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 postfix = "ab+cd-*";
Node root = buildTree(postfix);
System.out.println("Infix expression is:");
inOrder(root);
System.out.println("\nPostfix expression is:");
postOrder(root);
}
}
|
Python3
class node:
def __init__(self,c):
self.data=c
self.left=self.right=None
def add(a):
if (a == ''):
return ''
if a[0]>='a' and a[0]<='z':
return node(a[0]),a[1:]
else:
p=node(a[0])
p.left,q=add(a[1:])
p.right,q=add(q)
return p,q
def inr(p):
if (p == None):
return
else:
inr(p.left)
print(p.data,end=' ')
inr(p.right)
def postr(p):
if (p == None):
return
else:
postr(p.left)
postr(p.right)
print(p.data,end=' ')
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)
|
C#
using System;
using System.Collections.Generic;
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 postfix)
{
Stack<Node> stack = new Stack<Node>();
for (int i = 0; i < postfix.Length; i++) {
char c = postfix[i];
if (isOperator(c)) {
Node right = stack.Pop();
Node left = 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;
}
static void inOrder(Node node)
{
if (node != null) {
inOrder(node.left);
Console.Write(node.data + " ");
inOrder(node.right);
}
}
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 postfix = "ab+cd-*";
Node root = buildTree(postfix);
Console.WriteLine("Infix expression is:");
inOrder(root);
Console.WriteLine("\nPostfix expression is:");
postOrder(root);
}
}
|
Javascript
class Node {
constructor(c) {
this.data = c;
this.left = this.right = null;
}
}
function add(a) {
if (a === '') {
return '';
}
if (a.charCodeAt(0) >= 'a'.charCodeAt(0) && a.charCodeAt(0) <= 'z'.charCodeAt(0)) {
return [new Node(a[0]), a.slice(1)];
} else {
let p = new Node(a[0]);
let left = add(a.slice(1));
p.left = left[0];
let q = left[1];
let right = add(q);
p.right = right[0];
q = right[1];
return [p, q];
}
}
function inr(p) {
if (p === null) {
return;
} else {
inr(p.left);
console.log(p.data + ' ');
inr(p.right);
}
}
function postr(p) {
if (p === null) {
return;
} else {
postr(p.left);
postr(p.right);
console.log(p.data + ' ');
}
}
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)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!