The Wayback Machine - https://web.archive.org/web/20241119025317/https://www.geeksforgeeks.org/expression-tree/
Open In App

Expression Tree

Last Updated : 10 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

expressiontre

Inorder traversal of expression tree produces infix version of given postfix expression (same with postorder traversal it gives postfix expression)

Evaluating the expression represented by an expression tree: 

Let t be the expression tree
If  t is not null then
      If t.value is operand then  
                Return  t.value
      A = solve(t.left)
      B = solve(t.right)
 
      // calculate applies operator 't.value' 
      // on A and B, and returns value
      Return calculate(A, B, t.value)

Construction of Expression Tree: 

Now For constructing an expression tree we use a stack. We loop through input expression and do the following for every character. 

  1. If a character is an operand push that into the stack
  2. If a character is an operator pop two values from the stack make them its child and push the current node again.

In the end, the only element of the stack will be the root of an expression tree.

Examples:  

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

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

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

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.

A3f.png

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 nodes will be right subtree.        

Final Constructed Expression Tree is:

A4f.png

Below is the code of the above approach:  

Recommended Practice

Below is the implementation of the above approach:  

C++




// C++ program for expression tree
#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 {
    node* head = NULL;
 
public:
    void push(node*);
    node* pop();
    friend class expression_tree;
};
class expression_tree {
public:
    void inorder(node* x)
    {
        // cout<<"Tree in InOrder Traversal is: "<<endl;
        if (x == NULL)
            return;
        else {
            inorder(x->left);
            cout << x->value << "  ";
            inorder(x->right);
        }
    }
};
 
void Stack::push(node* x)
{
    if (head == NULL) {
        head = x;
    }
    // We are inserting here nodes at the top of the stack [following LIFO principle]
    else {
        x->next = head;
        head = x;
    }
}
node* Stack::pop()
{
    // Popping out the top most[ pointed with head] element
    node* p = head;
    head = head->next;
    return p;
}
int main()
{
    string s = "ABC*+D/";
    // If you  wish take input from user:
    //cout << "Insert Postorder Expression: " << endl;
    //cin >> s;
    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);
        }
    }
    cout << " The Inorder Traversal of Expression Tree: ";
    a.inorder(z);
    return 0;
}


C




#include <stdio.h>
#include <stdlib.h>
 
/* A binary tree node has data, pointer to left child
   and a pointer to right child */
struct node {
    char data;
    struct node* left;
    struct node* right;
    struct node* next;
};
 struct node *head=NULL;
/* Helper function that allocates a new node with the
   given data and NULL left and right pointers. */
struct node* newNode(char data)
{
    struct node* node
        = (struct node*)malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    node->next = NULL;
     
    return (node);
}
void printInorder(struct node* node)
{
    if (node == NULL)
        return;
    else{
    /* first recur on left child */
    printInorder(node->left);
 
    /* then print the data of node */
    printf("%c ", node->data);
 
    /* now recur on right child */
    printInorder(node->right);
    }
}
 
void push(struct node* x)
{
    if(head==NULL)
    head = x;
    else
    {
        (x)->next = head;
        head  = x;
    }
    // struct node* temp;
    // while(temp!=NULL)
    // {
    //     printf("%c ", temp->data);
    //     temp = temp->next;
    // }
}
struct node* pop()
{
    // Popping out the top most[ pointed with head] element
    struct node* p = head;
    head = head->next;
    return p;
}
int main()
{
    char s[] = {'A','B','C','*','+','D','/'};
    int l = sizeof(s) / sizeof(s[0]) ;
    struct node *x, *y, *z;
    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 = newNode(s[i]);
            x = pop();
            y = pop();
            z->left = y;
            z->right = x;
            push(z);
        }
        else {
            z = newNode(s[i]);
            push(z);
        }
    }
    printf(" The Inorder Traversal of Expression Tree: ");
    printInorder(z);
    return 0;
}


Java




import java.util.Stack;
 
class Node{
    char data;
    Node left,right;
    public Node(char data){
        this.data = data;
        left = right = null;
    }
}
 
public class Main {
    public static boolean isOperator(char ch){
        if(ch=='+' || ch=='-'|| ch=='*' || ch=='/' || ch=='^'){
            return true;
        }
        return false;
    }
    public static Node expressionTree(String postfix){
        Stack<Node> st = new Stack<Node>();
        Node t1,t2,temp;
 
        for(int i=0;i<postfix.length();i++){
            if(!isOperator(postfix.charAt(i))){
                temp = new Node(postfix.charAt(i));
                st.push(temp);
            }
            else{
                temp = new Node(postfix.charAt(i));
 
                t1 = st.pop();
                t2 = st.pop();
 
                temp.left = t2;
                temp.right = t1;
 
                st.push(temp);
            }
 
        }
        temp = st.pop();
        return temp;
    }
    public static void inorder(Node root){
        if(root==null) return;
 
        inorder(root.left);
        System.out.print(root.data);
        inorder(root.right);
    }
    public static void main(String[] args) {
        String postfix = "ABC*+D/";
 
        Node r = expressionTree(postfix);
        inorder(r);
    }
}


Python3




class Node:
    def __init__(self, value=None, left=None, right=None, next=None):
        self.value = value
        self.left = left
        self.right = right
        self.next = next
 
class Stack:
    def __init__(self):
        self.head = None
 
    def push(self, node):
        if not self.head:
            self.head = node
        else:
            node.next = self.head
            self.head = node
 
    def pop(self):
        if self.head:
            popped = self.head
            self.head = self.head.next
            return popped
        else:
            raise Exception("Stack is empty")
 
class ExpressionTree:
    def inorder(self, x):
        if not x:
            return
        self.inorder(x.left)
        print(x.value, end=" ")
        self.inorder(x.right)
 
def main():
    s = "ABC*+D/"
    stack = Stack()
    tree = ExpressionTree()
    for c in s:
        if c in "+-*/^":
            z = Node(c)
            x = stack.pop()
            y = stack.pop()
            z.left = y
            z.right = x
            stack.push(z)
        else:
            stack.push(Node(c))
    print("The Inorder Traversal of Expression Tree: ", end="")
    tree.inorder(stack.pop())
 
if __name__ == "__main__":
    main()


C#




using System;
using System.Collections.Generic;
 
 
class Node{
    public char data;
    public Node left,right;
    public Node(char data){
        this.data = data;
        left = right = null;
    }
}
 
public class GFG {
    public static bool isOperator(char ch){
        if(ch=='+' || ch=='-'|| ch=='*' || ch=='/' || ch=='^'){
            return true;
        }
        return false;
    }
    static Node expressionTree(String postfix){
        Stack<Node> st = new Stack<Node>();
        Node t1, t2, temp;
 
        for(int i = 0; i < postfix.Length; i++)
        {
            if(!isOperator(postfix[i])){
                temp = new Node(postfix[i]);
                st.Push(temp);
            }
            else{
                temp = new Node(postfix[i]);
 
                t1 = st.Pop();
                t2 = st.Pop();
 
                temp.left = t2;
                temp.right = t1;
 
                st.Push(temp);
            }
 
        }
        temp = st.Pop();
        return temp;
    }
    static void inorder(Node root){
        if(root == null) return;
 
        inorder(root.left);
        Console.Write(root.data);
        inorder(root.right);
    }
    public static void Main(String[] args)
    {
        String postfix = "ABC*+D/";
 
        Node r = expressionTree(postfix);
        inorder(r);
    }
}
 
// This code is contributed by 29AjayKumar


Javascript




// Javascript code for the above approach
class Node {
    constructor(value = null, left = null, right = null, next = null) {
        this.value = value;
        this.left = left;
        this.right = right;
        this.next = next;
    }
}
 
class Stack {
    constructor() {
        this.head = null;
    }
 
    push(node) {
        if (!this.head) {
            this.head = node;
        }
        else
        {
         // We are inserting here nodes at
         // the top of the stack [following LIFO principle]
            node.next = this.head;
            this.head = node;
        }
    }
 
    pop() {
        if (this.head) {
            let popped = this.head;
            this.head = this.head.next;
            return popped;
        } else {
            throw new Error("Stack is empty");
        }
    }
}
 
class ExpressionTree {
    inorder(x) {
        if (!x) {
            return;
        }
        this.inorder(x.left);
        console.log(x.value+" ");
        this.inorder(x.right);
    }
}
 
 
    let s = "ABC*+D/";
    let stack = new Stack();
    let tree = new ExpressionTree();
    for (let c of s) {
        if (c === "+" || c === "-" || c === "*" || c === "/" || c === "^") {
            let z = new Node(c);
            let x = stack.pop();
            let y = stack.pop();
            z.left = y;
            z.right = x;
            stack.push(z);
        } else {
            stack.push(new Node(c));
        }
    }
    console.log("The Inorder Traversal of Expression Tree: ");
    tree.inorder(stack.pop());
 
// This code is contributed by lokeshpotta20.


Output

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

Time complexity: O(n)
Auxiliary space: O(n)



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
Program to convert Infix notation to Expression Tree
Given a string representing infix notation. The task is to convert it to an expression tree.Expression Tree is a binary tree where the operands are represented by leaf nodes and operators are represented by intermediate nodes. No node can have a single child. Construction of Expression tree The algorithm follows a combination of shunting yard along
12 min read
Evaluation of Expression Tree
Given a simple expression tree, consisting of basic binary operators i.e., + , - ,* and / and some integers, evaluate the expression tree. Examples: Input: Root node of the below tree Output:100 Input: Root node of the below tree Output: 110 Recommended PracticeExpression TreeTry It! Approach: The approach to solve this problem is based on followin
9 min read
Convert Ternary Expression to a Binary Tree
Given a string that contains ternary expressions. The expressions may be nested, task is convert the given ternary expression to a binary Tree. Examples: Input : string expression = a?b:c Output : a / \ b cInput : expression = a?b?c:d:eOutput : a / \ b e / \ c dAsked In : Facebook Interview Idea is that we traverse a string make first character as
11 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
Convert a Generic Tree(N-array Tree) to Binary Tree
Prerequisite: Generic Trees(N-array Trees) In this article, we will discuss the conversion of the Generic Tree to a Binary Tree. Following are the rules to convert a Generic(N-array Tree) to a Binary Tree: The root of the Binary Tree is the Root of the Generic Tree.The left child of a node in the Generic Tree is the Left child of that node in the B
13 min read
Expression Evaluation
Evaluate an expression represented by a String. The expression can contain parentheses, you can assume parentheses are well-matched. For simplicity, you can assume only binary operations allowed are +, -, *, and /. Arithmetic Expressions can be written in one of three forms: Infix Notation: Operators are written between the operands they operate on
15 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
Identify and mark unmatched parenthesis in an expression
Given an expression, find and mark matched and unmatched parenthesis in it. We need to replace all balanced opening parenthesis with 0, balanced closing parenthesis with 1, and all unbalanced with -1.Examples: Input : ((a) Output : -10a1 Input : (a)) Output : 0a1-1 Input : (((abc))((d))))) Output : 000abc1100d111-1-1 The idea is based on a stack. W
6 min read
Map function and Lambda expression in Python to replace characters
Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input : str = 'grrksfoegrrks' c1 = e, c2 = r Output : geeksforgeeks Input : str = 'ratul' c1 = t, c2 = h Output : rahul We have an existing solution for this problem in C++. Please refer to Replace a character c1 with c2 and c2 with c1 in a string S. We can solve th
2 min read
Intersection of two arrays in Python ( Lambda expression and filter function )
Given two arrays, find their intersection. Examples: Input: arr1[] = [1, 3, 4, 5, 7] arr2[] = [2, 3, 5, 6] Output: Intersection : [3, 5] We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function. Implementation: C/C++ Code # Fun
1 min read
Expression contains redundant bracket or not
Given a string of balanced expressions, find if it contains a redundant parenthesis or not. A set of parenthesis is redundant if the same sub-expression is surrounded by unnecessary or multiple brackets. Print 'Yes' if redundant, else 'No'. Note: Expression may contain '+', '*', '-' and '/' operators. Given expression is valid and there are no whit
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
Arithmetic Expression Evaluation
The stack organization is very effective in evaluating arithmetic expressions. Expressions are usually represented in what is known as Infix notation, in which each operator is written between two operands (i.e., A + B). With this notation, we must distinguish between ( A + B )*C and A + ( B * C ) by using either parentheses or some operator-preced
2 min read
Maximum and Minimum Values of an Algebraic Expression
Given an algebraic expression of the form (x1 + x2 + x3 + . . . + xn) * (y1 + y2 + . . . + ym) and (n + m) integers. Find the maximum and minimum value of the expression using the given integers. Constraint : n <= 50 m <= 50 -50 <= x1, x2, .. xn <= 50 Examples : Input : n = 2, m = 2 arr[] = {1, 2, 3, 4} Output : Maximum : 25 Minimum : 2
14 min read
Balanced expression with replacement
Given a string that contains only the following => ‘{‘, ‘}’, ‘(‘, ‘)’, ‘[’, ‘]’. At some places there is ‘X’ in place of any bracket. Determine whether by replacing all ‘X’s with appropriate bracket, is it possible to make a valid bracket sequence. Prerequisite: Balanced Parenthesis Expression Examples: Input : S = "{(X[X])}" Output : Balanced T
13 min read
Check for balanced parentheses in an expression | O(1) space
Given a string of length n having parentheses in it, your task is to find whether given string has balanced parentheses or not. Please note there is constraint on space i.e. we are allowed to use only O(1) extra space. Also See : Check for balanced parentheses Examples: Input : (())[] Output : Yes Input : ))(({}{ Output : No If k = 1, then we will
15+ min read
Find the missing digit x from the given expression
Given an alphanumeric string, consisting of a single alphabet X, which represents an expression of the form: A operator B = C where A, B and C denotes integers and the operator can be either of +, -, * or / The task is to evaluate the missing digit X present in any of the integers A, B and C such that the given expression holds to be valid. Example
9 min read
Deriving the expression of Fibonacci Numbers in terms of golden ratio
Prerequisites: Generating Functions, Fibonacci Numbers, Methods to find Fibonacci numbers. The method of using Generating Functions to solve the famous and useful Fibonacci Numbers' recurrence has been discussed in this post. The Generating Function is a powerful tool for solving a wide variety of mathematical problems, including counting problems.
4 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
Solve the Logical Expression given by string
Given string str representing a logical expression which consists of the operators | (OR), & (AND),! (NOT) , 0, 1 and, only (i.e. no space between characters). The task is to print the result of the logical expression. Examples: Input: str = "[[0,&,1],|,[!,1]]" Output: 0 Explanation:[[0,&,1],|,[!,1]] [[0,&,1],|,0] [[0,&,1],|,0]
5 min read
Program to evaluate the expression (√X+1)^6 + (√X-1)^6
Given a number [Tex]X [/Tex]. The task is to find the value of the below expression for the given value of [Tex]X [/Tex]. [Tex](\sqrt[]{X} +1)^6 + (\sqrt[]{X}-1)^6[/Tex] Examples: Input: X = ?2 Output: 198 Explanation: [Tex]2[(\sqrt[]{2})^6 + 15 (\sqrt[]{2})^4 + 15\sqrt[]{2})^2 + 1] [/Tex]= 198Input: X = 3 Output: 4160 Approach: The idea is to use
3 min read
Find a permutation of 2N numbers such that the result of given expression is exactly 2K
Given two integers N and K, the task is to find a permutation of first 2*N natural numbers such that the following equation is satisfied. [Tex]\sum\limits_{i=1}^N |A_{2i-1}-A_{2i}| - |\sum\limits_{i=1}^N A_{2i-1}-A_{2i}|=2K [/Tex]Note: The value of K will always be less than or equal to N.Examples: Input : N = 1, K = 0 Output : 1 2 The result of th
5 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
Maximize the value of the given expression
Given three non-zero integers a, b and c. The task is to find the maximum value possible by putting addition and multiplication signs between them in any order. Note: Rearrangement of integers is allowed but addition and multiplication sign must be used once. Braces can also be placed between equations as per your need. Examples: Input: a = 2, b =
8 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
Check if expression contains redundant bracket or not | Set 2
Given a string of balanced expressions, find if it contains a redundant parenthesis or not. A set of parenthesis is redundant if the same sub-expression is surrounded by unnecessary or multiple brackets. Print ‘Yes’ if redundant else ‘No’.Note: Expression may contain '+', ‘*‘, ‘–‘ and ‘/‘ operators. Given expression is valid and there are no white
5 min read
Maximize the Expression | Bit Manipulation
Given two positive integers A and B. Let's define D such that B AND D = D. The task is to maximize the expression A XOR D.Examples: Input: A = 11 B = 4 Output: 15 Take D = 4 as (B AND D) = (4 AND 4) = 4. Also, (A XOR D) = (11 XOR 4) = 15 which is the maximum according to the given condition. Input: A = 9 and B = 13 Output: 13 Naive approach: Since
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg