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

Evaluation of Expression Tree

Last Updated : 10 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

pic2

Output:100

Input: Root node of the below tree

pic1

Output: 110

Recommended Practice

Approach: The approach to solve this problem is based on following observation:

As all the operators in the tree are binary, hence each node will have either 0 or 2 children. As it can be inferred from the examples above, all the integer values would appear at the leaf nodes, while the interior nodes represent the operators.

Therefore we can do inorder traversal of the binary tree and evaluate the expression as we move ahead.

To evaluate the syntax tree, a recursive approach can be followed.

Algorithm:

  • Let t be the syntax tree
  • If  t is not null then      
    • If t.info is operand then  
      • Return  t.info
    • Else
      • A = solve(t.left)
      • B = solve(t.right)
      • return A operator B, where operator is the info contained in t

Below is the implementation of the above approach:

C++




// C++ program to evaluate an expression tree
#include <bits/stdc++.h>
using namespace std;
 
// Class to represent the nodes of syntax tree
class node
{
public:
    string info;
    node *left = NULL, *right = NULL;
    node(string x)
    {
        info = x;
    }
};
 
// Utility function to return the integer value
// of a given string
int toInt(string s)
{
    int num = 0;
         
    // Check if the integral value is
    // negative or not
    // If it is not negative, generate the number
    // normally
    if(s[0]!='-')
        for (int i=0; i<s.length(); i++)
            num = num*10 + (int(s[i])-48);
    // If it is negative, calculate the +ve number
    // first ignoring the sign and invert the
    // sign at the end
    else
    {
      for (int i=1; i<s.length(); i++)
        num = num*10 + (int(s[i])-48);
      num = num*-1;
    }
     
    return num;
}
 
// This function receives a node of the syntax tree
// and recursively evaluates it
int eval(node* root)
{
    // empty tree
    if (!root)
        return 0;
 
    // leaf node i.e, an integer
    if (!root->left && !root->right)
        return toInt(root->info);
 
    // Evaluate left subtree
    int l_val = eval(root->left);
 
    // Evaluate right subtree
    int r_val = eval(root->right);
 
    // Check which operator to apply
    if (root->info=="+")
        return l_val+r_val;
 
    if (root->info=="-")
        return l_val-r_val;
 
    if (root->info=="*")
        return l_val*r_val;
 
    return l_val/r_val;
}
 
//driver function to check the above program
int main()
{
    // create a syntax tree
    node *root = new node("+");
    root->left = new node("*");
    root->left->left = new node("5");
    root->left->right = new node("-4");
    root->right = new node("-");
    root->right->left = new node("100");
    root->right->right = new node("20");
    cout << eval(root) << endl;
 
    delete(root);
 
    root = new node("+");
    root->left = new node("*");
    root->left->left = new node("5");
    root->left->right = new node("4");
    root->right = new node("-");
    root->right->left = new node("100");
    root->right->right = new node("/");
    root->right->right->left = new node("20");
    root->right->right->right = new node("2");
 
    cout << eval(root);
    return 0;
}


Java




// Java program to evaluate expression tree
import java.lang.*;
 
class GFG{
     
Node root;
 
// Class to represent the nodes of syntax tree
public static class Node
{
    String data;
    Node left, right;
 
    Node(String d)
    {
        data = d;
        left = null;
        right = null;
    }
}
 
private static int toInt(String s)
{
    int num = 0;
 
    // Check if the integral value is
    // negative or not
    // If it is not negative, generate
    // the number normally
    if (s.charAt(0) != '-')
        for(int i = 0; i < s.length(); i++)
            num = num * 10 + ((int)s.charAt(i) - 48);
             
    // If it is negative, calculate the +ve number
    // first ignoring the sign and invert the
    // sign at the end
    else
    {
        for(int i = 1; i < s.length(); i++)
          num = num * 10 + ((int)(s.charAt(i)) - 48);
        num = num * -1;
    }
    return num;
}
 
// This function receives a node of the syntax
// tree and recursively evaluate it
public static int evalTree(Node root)
{
     
    // Empty tree
    if (root == null)
        return 0;
 
    // Leaf node i.e, an integer
    if (root.left == null && root.right == null)
        return toInt(root.data);
 
    // Evaluate left subtree
    int leftEval = evalTree(root.left);
 
    // Evaluate right subtree
    int rightEval = evalTree(root.right);
 
    // Check which operator to apply
    if (root.data.equals("+"))
        return leftEval + rightEval;
 
    if (root.data.equals("-"))
        return leftEval - rightEval;
 
    if (root.data.equals("*"))
        return leftEval * rightEval;
 
    return leftEval / rightEval;
}
 
// Driver code
public static void main(String[] args)
{
     
    // Creating a sample tree
    Node root = new Node("+");
    root.left = new Node("*");
    root.left.left = new Node("5");
    root.left.right = new Node("-4");
    root.right = new Node("-");
    root.right.left = new Node("100");
    root.right.right = new Node("20");
    System.out.println(evalTree(root));
 
    root = null;
 
    // Creating a sample tree
    root = new Node("+");
    root.left = new Node("*");
    root.left.left = new Node("5");
    root.left.right = new Node("4");
    root.right = new Node("-");
    root.right.left = new Node("100");
    root.right.right = new Node("/");
    root.right.right.left = new Node("20");
    root.right.right.right = new Node("2");
    System.out.println(evalTree(root));
}
}
 
// This code is contributed by Ankit Gupta


Python3




# Python program to evaluate expression tree
 
# Class to represent the nodes of syntax tree
 
 
class node:
    def __init__(self, value):
        self.left = None
        self.data = value
        self.right = None
 
# This function receives a node of the syntax tree
# and recursively evaluate it
 
 
def evaluateExpressionTree(root):
 
    # empty tree
    if root is None:
        return 0
 
    # leaf node
    if root.left is None and root.right is None:
        return int(root.data)
 
    # evaluate left tree
    left_sum = evaluateExpressionTree(root.left)
 
    # evaluate right tree
    right_sum = evaluateExpressionTree(root.right)
 
    # check which operation to apply
    if root.data == '+':
        return left_sum + right_sum
 
    elif root.data == '-':
        return left_sum - right_sum
 
    elif root.data == '*':
        return left_sum * right_sum
 
    else:
        return left_sum // right_sum
 
 
# Driver function to test above problem
if __name__ == '__main__':
 
    # creating a sample tree
    root = node('+')
    root.left = node('*')
    root.left.left = node('5')
    root.left.right = node('-4')
    root.right = node('-')
    root.right.left = node('100')
    root.right.right = node('20')
    print (evaluateExpressionTree(root))
 
    root = None
 
    # creating a sample tree
    root = node('+')
    root.left = node('*')
    root.left.left = node('5')
    root.left.right = node('4')
    root.right = node('-')
    root.right.left = node('100')
    root.right.right = node('/')
    root.right.right.left = node('20')
    root.right.right.right = node('2')
    print (evaluateExpressionTree(root))
 
# This code is contributed by Harshit Sidhwa


C#




// C# program to evaluate expression tree
using System;
 
public class GFG
{
 
    // Class to represent the nodes of syntax tree
    public class Node {
        public
       String data;
              public
       Node left, right;
 
        public Node(String d) {
            data = d;
            left = null;
            right = null;
        }
    }
 
    private static int toInt(String s) {
        int num = 0;
 
        // Check if the integral value is
        // negative or not
        // If it is not negative, generate
        // the number normally
        if (s[0] != '-')
            for (int i = 0; i < s.Length; i++)
                num = num * 10 + ((int) s[i] - 48);
 
        // If it is negative, calculate the +ve number
        // first ignoring the sign and invert the
        // sign at the end
        else {
          for (int i = 1; i < s.Length; i++)
            num = num * 10 + ((int) (s[i]) - 48);
          num = num * -1;
        }
        return num;
    }
 
    // This function receives a node of the syntax
    // tree and recursively evaluate it
    public static int evalTree(Node root) {
 
        // Empty tree
        if (root == null)
            return 0;
 
        // Leaf node i.e, an integer
        if (root.left == null && root.right == null)
            return toInt(root.data);
 
        // Evaluate left subtree
        int leftEval = evalTree(root.left);
 
        // Evaluate right subtree
        int rightEval = evalTree(root.right);
 
        // Check which operator to apply
        if (root.data.Equals("+"))
            return leftEval + rightEval;
 
        if (root.data.Equals("-"))
            return leftEval - rightEval;
 
        if (root.data.Equals("*"))
            return leftEval * rightEval;
 
        return leftEval / rightEval;
    }
 
    // Driver code
    public static void Main(String[] args) {
 
        // Creating a sample tree
        Node root = new Node("+");
        root.left = new Node("*");
        root.left.left = new Node("5");
        root.left.right = new Node("-4");
        root.right = new Node("-");
        root.right.left = new Node("100");
        root.right.right = new Node("20");
        Console.WriteLine(evalTree(root));
 
        root = null;
 
        // Creating a sample tree
        root = new Node("+");
        root.left = new Node("*");
        root.left.left = new Node("5");
        root.left.right = new Node("4");
        root.right = new Node("-");
        root.right.left = new Node("100");
        root.right.right = new Node("/");
        root.right.right.left = new Node("20");
        root.right.right.right = new Node("2");
        Console.WriteLine(evalTree(root));
    }
}
 
// This code is contributed by umadevi9616


Javascript




<script>
// javascript program to evaluate expression tree
    var root;
 
    // Class to represent the nodes of syntax tree
     class Node {
        constructor(val) {
            this.data = val;
            this.left = null;
            this.right = null;
        }
    }
 
     function toInt( s) {
        var num = 0;
  
        // Check if the integral value is
        // negative or not
        // If it is not negative, generate
        // the number normally
        if (s.charAt(0) != '-')
            for (i = 0; i < s.length; i++)
                num = num * 10 + ( s.charCodeAt(i) - 48);
 
        // If it is negative, calculate the +ve number
        // first ignoring the sign and invert the
        // sign at the end
        else {
          for (i = 1; i < s.length; i++)
              num = num * 10 + (s.charCodeAt(i) - 48);
          num = num * -1;
        }
        return num;
    }
 
    // This function receives a node of the syntax
    // tree and recursively evaluate it
    function evalTree(root) {
 
        // Empty tree
        if (root == null)
            return 0;
 
        // Leaf node i.e, an integer
        if (root.left == null && root.right == null)
            return toInt(root.data);
 
        // Evaluate left subtree
        var leftEval = evalTree(root.left);
 
        // Evaluate right subtree
        var rightEval = evalTree(root.right);
 
        // Check which operator to apply
        if (root.data === ("+"))
            return leftEval + rightEval;
 
        if (root.data === ("-"))
            return leftEval - rightEval;
 
        if (root.data === ("*"))
            return leftEval * rightEval;
 
        return leftEval / rightEval;
    }
 
    // Driver code
     
 
        // Creating a sample tree
        var root = new Node("+");
        root.left = new Node("*");
        root.left.left = new Node("5");
        root.left.right = new Node("-4");
        root.right = new Node("-");
        root.right.left = new Node("100");
        root.right.right = new Node("20");
        document.write(evalTree(root));
 
        root = null;
 
        // Creating a sample tree
        root = new Node("+");
        root.left = new Node("*");
        root.left.left = new Node("5");
        root.left.right = new Node("4");
        root.right = new Node("-");
        root.right.left = new Node("100");
        root.right.right = new Node("/");
        root.right.right.left = new Node("20");
        root.right.right.right = new Node("2");
        document.write("<br/>"+evalTree(root));
 
// This code is contributed by gauravrajput1
</script>


Output

60
110

Time Complexity: O(n), as each node is visited once.
Auxiliary Space: O(n)



Similar Reads

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
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
Evaluation of Postfix Expression
Given a postfix expression, the task is to evaluate the postfix expression. Postfix expression: The expression of the form "a b operator" (ab+) i.e., when a pair of operands is followed by an operator. Examples: Input: str = "2 3 1 * + 9 -"Output: -4Explanation: If the expression is converted into an infix expression, it will be 2 + (3 * 1) - 9 = 5
15+ 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
Evaluation of Prefix Expressions
Prefix and Postfix expressions can be evaluated faster than an infix expression. This is because we don't need to process any brackets or follow operator precedence rule. In postfix and prefix expressions which ever operator comes before will be evaluated first, irrespective of its priority. Also, there are no brackets in these expressions. As long
13 min read
Evaluation of Risk in Investments
Given two investment options A and B, we have to find the less risky investment of the two. The two investments A and B are each represented by an array. Each element in the array is a probable investment outcome. Thus each element in the array is a pair of two values. The first value is the amount of money received and the second value is the prob
12 min read
Remainder Evaluation
Given two positive integers Num1 and Num2, the task is to find the remainder when Num1 is divided by Num2. Examples: Input: Num1 = 11, Num2 = 3Output: 2Explanation: 3) 11 (3 - 9 --------- 2 -&gt; Remainder ---------- Input: Num1 = 15, Num2 = 3Output: 0 Approach 1: The problem can be solved by using the modulus operator. Modulus operator returns the
5 min read
Grid Evolution and Query Evaluation
Given a grid of dimensions n rows and m columns, where each element initially contains an integer from 0 to k-1. The grid evolves over time, with each element undergoing the transformation (grid[i][j] + 1) % k after each unit of time. You are also provided with a series of queries, each defined by [t, val, lx, ly, rx, ry], the task is to determine,
13 min read
Horner's Method for Polynomial Evaluation
Given a polynomial of the form cnxn + cn-1xn-1 + cn-2xn-2 + ... + c1x + c0 and a value of x, find the value of polynomial for a given value of x. Here cn, cn-1, .. are integers (may be negative) and n is a positive integer.Input is in the form of an array say poly[] where poly[0] represents coefficient for xn and poly[1] represents coefficient for
6 min read
Introduction to Evaluation Function of Minimax Algorithm in Game Theory
Prerequisite: Minimax Algorithm in Game TheoryAs seen in the above article, each leaf node had a value associated with it. We had stored this value in an array. But in the real world when we are creating a program to play Tic-Tac-Toe, Chess, Backgammon, etc. we need to implement a function that calculates the value of the board depending on the pla
8 min read
three90RightbarBannerImg