The Wayback Machine - https://web.archive.org/web/20241124065158/https://www.geeksforgeeks.org/expression-trees-using-classes-in-c-with-implementation/
Open In App

Expression Trees Using Classes in C++ with Implementation

Last Updated : 25 Nov, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: Expression Tree

The expression tree is a binary tree in which each internal node corresponds to the operator and each leaf node corresponds to the operand so for example expression tree for 3 + ((5+9)*2) would be:

Expression Tree

In expression trees, leaf nodes are operands and non-leaf nodes are operators. That means an expression tree is a binary tree where internal nodes are operators and leaves are operands. An expression tree consists of binary expressions. But for a unary operator, one subtree will be empty. 

Construction of Expression Tree:

  • The user will provide a postfix expression for which the program will construct the expression tree. 
  • Inorder traversal of binary tree/expression tree will provide Infix expression of the given input.

Example:  

Input:  A B C*+ D/
Output: A + B * C / D

Step 1: The first three symbols are operands, so create tree nodes and push pointers to them onto a stack as shown below.

Create tree nodes

Step 2: In the Next step, an operator ‘*’ will going read, so two pointers to trees are popped, a new tree is formed and a pointer to it is pushed onto the stack

New tree is formed

Step 3: In the Next step,  an operator ‘+’ will read, so two pointers to trees are popped, a new tree is formed and a pointer to it is pushed onto the stack.

push on stack

Step 4: Similarly, as above cases first we push ‘D’ into the stack and then in the last step first, will read ‘/’ and then as previous step topmost element will pop out and then will be right subtree of root  ‘/’ and other node will be right subtree.

Final Constructed Expression Tree is:

Final Constructed expression tree

Below is the C++ program to implement the above approach:

C++




// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
class node {
public:
    char value;
    node* left;
    node* right;
    node* next = NULL;
    node(char c)
    {
        this->value = c;
        left = NULL;
        right = NULL;
    }
    node()
    {
        left = NULL;
        right = NULL;
    }
    friend class Stack;
    friend class expression_tree;
};
 
// Class stack to hold
// tree nodes
class Stack {
    node* head = NULL;
 
public:
    void push(node*);
    node* pop();
    friend class expression_tree;
};
 
// Class to implement
// inorder traversal
class expression_tree {
public:
    // Function to implement
    // inorder traversal
    void inorder(node* x)
    {
        if (x == NULL)
            return;
        else {
            inorder(x->left);
            cout << x->value << "  ";
            inorder(x->right);
        }
    }
};
 
// Function to push values
// onto the stack
void Stack::push(node* x)
{
    if (head == NULL) {
        head = x;
    }
 
    // We are inserting nodes at
    // the top of the stack [
    // following LIFO principle]
    else {
        x->next = head;
        head = x;
    }
}
 
// Function to implement pop
// operation in the stack
node* Stack::pop()
{
    // Popping out the top most[
    // pointed with head] element
    node* p = head;
    head = head->next;
    return p;
}
 
// Driver code
int main()
{
    // Postfix expression
    string s = "ABC*+D/";
 
    Stack e;
    expression_tree a;
    node *x, *y, *z;
    int l = s.length();
 
    for (int i = 0; i < l; i++) {
        // if read character is operator
        // then popping two other elements
        // from stack and making a binary
        // tree
        if (s[i] == '+' || s[i] == '-'
            || s[i] == '*' || s[i] == '/'
            || s[i] == '^') {
            z = new node(s[i]);
            x = e.pop();
            y = e.pop();
            z->left = y;
            z->right = x;
            e.push(z);
        }
        else {
            z = new node(s[i]);
            e.push(z);
        }
    }
 
    // Print the inorder traversal
    cout << " The Inorder Traversal of Expression Tree: ";
    a.inorder(z);
    return 0;
}


Output:

The Inorder Traversal of Expression Tree: A + B * C / D



Similar Reads

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 +
11 min read
Introduction to Generic Trees (N-ary Trees)
Generic trees are a collection of nodes where each node is a data structure that consists of records and a list of references to its children(duplicate references are not allowed). Unlike the linked list, each node stores the address of multiple nodes. Every node stores address of its children and the very first node's address will be stored in a s
5 min read
Total number of possible Binary Search Trees and Binary Trees with n keys
Given an integer n, the task is to find the total number of unique Binary Search trees And unique Binary trees that can be made using values from 1 to n. Examples: Input: n = 3 Output: BST = 5 BT = 30Explanation: For n = 3, Totol number of binary search tree will be 5 and total Binary tree will b 30. Input: n = 5 Output: BST = 42 BT = 5040Explanati
7 min read
B*-Trees implementation in C++
B*-tree of order m is a search tree that is either empty or that satisfies three properties: The root node has minimum two and maximum 2 floor ((2m-2)/3) +1 children Other internal nodes have the minimum floor ((2m-1)/3) and maximum m children All external nodes are on the same level. The advantage of using B* trees over B-trees is a unique feature
10 min read
Implementation of Dynamic Segment Trees with Poly Hash Tables
Dynamic Segment Trees with Poly Hash Tables is a data structure that combines the benefits of both dynamic segment trees and hash tables to efficiently handle range queries on an array of elements. To understand this topic, let's start with an example. Consider an array of N elements {1, 2, 3, ..., N}. We want to support two operations on this arra
15+ min read
Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)
We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1} Output: 11 Explanation: 11 is the sm
11 min read
How to validate MAC address using Regular Expression
Given string str, the task is to check whether the given string is a valid MAC address or not by using Regular Expression. A valid MAC address must satisfy the following conditions: It must contain 12 hexadecimal digits.One way to represent them is to form six pairs of the characters separated with a hyphen (-) or colon(:). For example, 01-23-45-67
6 min read
How to validate Indian driving license number using Regular Expression
Given string str, the task is to check whether the given string is a valid Indian driving license number or not by using Regular Expression.The valid Indian driving license number must satisfy the following conditions: It should be 16 characters long (including space or hyphen (-)).The driving license number can be entered in any of the following f
7 min read
Smallest expression to represent a number using single digit
Given a number N and a digit D, we have to form an expression or equation that contains only D and that expression evaluates to N. Allowed operators in an expression are +, -, *, and / . Find the minimum length expression that satisfies the condition above and D can only appear in the expression at most 10(limit) times. Hence limit the values of N
15+ min read
How to validate CVV number using Regular Expression
Given string str, the task is to check whether it is a valid CVV (Card Verification Value) number or not by using Regular Expression. The valid CVV (Card Verification Value) number must satisfy the following conditions: It should have 3 or 4 digits.It should have a digit between 0-9.It should not have any alphabet or special characters. Examples: I
5 min read
Check if a String Contains Only Alphabets in Java Using Lambda Expression
Lambda expressions basically express instances of functional interfaces (An interface with a single abstract method is called functional interface. An example is java.lang.Runnable). lambda expressions implement the only abstract function and therefore implement functional interfaces. Given a String, we just need to iterate over characters again th
3 min read
Print the balanced bracket expression using given brackets
Given four integers a, b, c and d which signifies the number of four types of brackets. "((""()"")(""))" The task is to print any balanced bracket expression using all the given brackets. If we cannot form a balanced bracket expression then print -1. In case of multiple answers, print any one. Examples: Input: a = 3, b = 1, c = 4, d = 3 Output: (((
6 min read
How to validate SSN (Social Security Number) using Regular Expression
Given string str, the task is to check whether the given string is valid SSN (Social Security Number) or not by using Regular Expression. The valid SSN (Social Security Number) must satisfy the following conditions: It should have 9 digits.It should be divided into 3 parts by hyphen (-).The first part should have 3 digits and should not be 000, 666
6 min read
Validate Corporate Identification Number (CIN) using Regular Expression
Given some Corporate Identification Number, the task is to check if they are valid or not using regular expressions. Rules for the valid CIN are: CIN is a 21 digits alpha-numeric code.It starts with either alphabet letter U or L.Next five characters are reserved for digits (0-9).Next two places are occupied by alphabet letters(A-Z-a-z).Next four pl
6 min read
How to validate PAN Card number using Regular Expression
Given string str of alphanumeric characters, the task is to check whether the string is a valid PAN (Permanent Account Number) Card number or not by using Regular Expression.The valid PAN Card number must satisfy the following conditions: It should be ten characters long.The first five characters should be any upper case alphabets.The next four-cha
6 min read
How to validate time in 24-hour format using Regular Expression
Given a string str, the task is to check whether the string is valid time in 24-hour format or not by using Regular Expression. The valid time in the 24-hour format must satisfy the following conditions. It should start from 0-23 or 00-23.It should be followed by a ':'(colon).It should be followed by two digits from 00 to 59.It should not end with
6 min read
How to validate pin code of India using Regular Expression
Given a string of positive number ranging from 0 to 9, the task is to check whether the number is valid pin code or not by using a Regular Expression. The valid pin code of India must satisfy the following conditions. It can be only six digits.It should not start with zero.First digit of the pin code must be from 1 to 9.Next five digits of the pin
6 min read
How to validate Hexadecimal Color Code using Regular Expression
Given string str, the task is to check whether the string is valid hexadecimal colour code or not by using Regular Expression. The valid hexadecimal color code must satisfy the following conditions. It should start from '#' symbol.It should be followed by the letters from a-f, A-F and/or digits from 0-9.The length of the hexadecimal color code shou
6 min read
How to check string is alphanumeric or not using Regular Expression
Given string str, the task is to check whether the string is alphanumeric or not by using Regular Expression. An alphanumeric string is a string that contains only alphabets from a-z, A-Z and some numbers from 0-9. Examples: Input: str = "GeeksforGeeks123" Output: true Explanation: This string contains all the alphabets from a-z, A-Z, and the numbe
5 min read
How to check Aadhaar number is valid or not using Regular Expression
Given string str, the task is to check whether the given string is a valid Aadhaar number or not by using Regular Expression. The valid Aadhaar number must satisfy the following conditions: It should have 12 digits.It should not start with 0 and 1.It should not contain any alphabet and special characters.It should have white space after every 4 dig
5 min read
How to validate image file extension using Regular Expression
Given string str, the task is to check whether the given string is a valid image file extension or not by using Regular Expression. The valid image file extension must specify the following conditions: It should start with a string of at least one character.It should not have any white space.It should be followed by a dot(.).It should be end with a
5 min read
How to validate GST (Goods and Services Tax) number using Regular Expression
Given string str, the task is to check whether the given string is a valid GST (Goods and Services Tax) number or not using Regular Expression. The valid GST (Goods and Services Tax) number must satisfy the following conditions: It should be 15 characters long.The first 2 characters should be a number.The next 10 characters should be the PAN number
6 min read
How to validate HTML tag using Regular Expression
Given string str, the task is to check whether it is a valid HTML tag or not by using Regular Expression.The valid HTML tag must satisfy the following conditions: It should start with an opening tag (<).It should be followed by a double quotes string or single quotes string.It should not allow one double quotes string, one single quotes string o
6 min read
How to validate IFSC Code using Regular Expression
Given string str, the task is to check whether the given string is a valid IFSC (Indian Financial System) Code or not by using Regular Expression. The valid IFSC (Indian Financial System) Code must satisfy the following conditions: It should be 11 characters long.The first four characters should be upper case alphabets.The fifth character should be
8 min read
How to validate MasterCard number using Regular Expression
Given string str, the task is to check whether the given string is a valid Master Card number or not by using Regular Expression. The valid Master Card number must satisfy the following conditions. It should be 16 digits long.It should start with either two digits numbers may range from 51 to 55 or four digits numbers may range from 2221 to 2720.In
7 min read
How to validate Visa Card number using Regular Expression
Given a string str, the task is to check whether the given string is a valid Visa Card number or not by using Regular Expression. The valid Visa Card number must satisfy the following conditions: It should be 13 or 16 digits long, new cards have 16 digits and old cards have 13 digits.It should start with 4.If the cards have 13 digits the next twelv
6 min read
How to validate GUID (Globally Unique Identifier) using Regular Expression
Given string str, the task is to check whether the given string is a valid GUID (Globally Unique Identifier) or not by using Regular Expression.The valid GUID (Globally Unique Identifier) must specify the following conditions: It should be a 128-bit number.It should be 36 characters (32 hexadecimal characters and 4 hyphens) long.It should be displa
6 min read
Parity of the given mathematical expression using given N numbers
Given N positive integers A1, A2, ..., AN, the task is to determine the parity of the expression S. For the given N numbers, the expression S is given as: [Tex]S = 1 + \sum_{i=1}^{N}A_i + \sum_{i=1}^{N}(A_i * A_{i+1}) + \sum_{i=1}^{N}(A_i * A_{i+1} * A_{i+2}) + ...+ (A_1 * A_2 * A_3 * ... * A_N) [/Tex] Examples: Input: N = 3, A1 = 2, A2 = 3, A3 = 1
5 min read
Check if an URL is valid or not using Regular Expression
Given a URL as a character string str of size N.The task is to check if the given URL is valid or not.Examples : Input : str = "https://www.geeksforgeeks.org/" Output : Yes Explanation : The above URL is a valid URL.Input : str = "https:// www.geeksforgeeks.org/" Output : No Explanation : Note that there is a space after https://, hence the URL is
4 min read
Validate week days using Regular Expression
Given some Weekdays, the task is to check if they are valid or not using regular expressions. Rules for the valid Weekdays : It should contain specific only words as a string. They are mentioned below:Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday.Mon, Tues, Wed, Thurs, Fri, Sat, Sun. Mon., Tues., Wed., Thurs., Fri., Sat., Sun.
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg