DAA: Expression Trees

Expression Trees

Expression trees are those in which the leaf nodes have the values to be operated, and internal nodes contain the operator on which the leaf node will be performed.

Example: 3 + ((5 + 9) * 2) will have an expression tree as follows:

Expression Trees in DAA

Take a tree T and if it is not null

      If t.value is an operand, then. 

                Return  t.value

      A = solve(t.left)  // Recur for left

      B = solve(t.right) // Recur for right

      --> Compute applies operator 't.value' on A and B, and return value

      Return calculate(A, B, t.value)

Ways and data structure to create an expression tree is

The optimal data structure to be used here is stack. Iterate in the postfix expression and do the following steps:

  1. If we strike an operand in expression, push in the stack.
  2. If we take and pop two values from stack, push them in current mode by making them child.

C++ code:

 #include <bits/stdc++.h>
 using namespace std;
 // node class for expression tree
 class node {
 public:
     char data;
     node *left, *right;
     node(char data)
     {
         this->data = data;
         left = NULL;
         right = NULL;
     }
 };
 //expression tree class
 class exp_tree {
     string postfix_exp;
     node* root;
 public:
     exp_tree(string postfix_exp)
     {
         this->postfix_exp = postfix_exp;
         root = NULL;
         create_tree(postfix_exp);
     }
 private:
     bool is_operator(char c)
     {
         if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^') // if given char is operator
         {
             return true; // then return true
         }
         return false; // else return false
     }
     void create_tree(string exp)
     {
         int len = exp.length();
         stack<node*> s;
         root = new node(exp[len - 1]);
         s.push(root);
         for (int i = len - 2; i >= 0; i--) // travel on rest of the postfix expression
         {
             node* curr_node = s.top();
             if (curr_node->right == NULL) // if right node of current node is NULL
             {
                 node* temp = new node(exp[i]);
                 curr_node->right = temp;
                 if (is_operator(exp[i])) {
                     s.push(temp);
                 }
             }
             else             {
                 node* temp = new node(exp[i]);
                 curr_node->left = temp;
                 // if no child node of current node is NULL
                 s.pop(); // pop current from stack
                 if (is_operator(exp[i])) {
                     s.push(temp);
                 }
             }
         }
     }
     void inorder_traversal(node* head) // inorder traversal of expression tree
     {
         // inorder traversal => left,root,right
         if (head->left != NULL) {
             inorder_traversal(head->left);
         }
         cout << head->data << " ";
         if (head->right != NULL) {
             inorder_traversal(head->right);
         }
         return;
     }
 public:
     void infix_exp() // inorder traversal of expression tree will give infix expression
     {
         inorder_traversal(root);
         cout << endl;
         return;
     }
 };
 int main()
 {
     string postfix_exp = "ab+ef*g*-";
     exp_tree et(postfix_exp);
     et.infix_exp();
     return 0;
 } 

Output:

a + b - e * f * g

Python code:

 #stack class
 class stack:
     def __init__(self):
         self.arr = []
     def push(self, data):
         self.arr.append(data)
     def pop(self):
         try:
             return self.arr.pop(-1)
         except:
             pass
     def top(self):
         try:
             return self.arr[-1]
         except:
             pass
     def size(self):
         return len(self.arr)
 #node class for expression tree
 class node:
     def __init__(self, data):
         self.data = data
         self.left = None
         self.right = None
 #expression tree class
 class exp_tree:
     def __init__(self, postfix_exp):
         self.exp = postfix_exp
         self.root = None
         self.createTree(self.exp)
     def isOperator(self, char):
         optr = ['+', '-', '*', '/', '^']
         if char in optr:  # if given char is operator
             return True  # then return true
         return False  # else return false
     def createTree(self, exp):
         s = stack()  # store those operator node whose any child node is NULL
         self.root = node(exp[-1])
 #last character of postfix expression is always an operator
         s.push(self.root)
 #travel on rest of the postfix expression
         for i in "".join(reversed(exp[:-1])):
             curr_node = s.top()
             if not curr_node.right:  # if right node of current node is NULL
                 temp = node(i)
                 curr_node.right = temp
                 if self.isOperator(i):
                     s.push(temp)
             else:  # if left node of current node is NULL
                 temp = node(i)
                 curr_node.left = temp
 #if no child node of current node is NULL
                 s.pop()  # pop current from stack
                 if self.isOperator(i):
                     s.push(temp)
     def inorder(self, head):  # inorder traversal of expression tree
 #inorder traversal = > left, root, right
         if head.left:
             self.inorder(head.left)
         print(head.data, end=" ")
         if head.right:
             self.inorder(head.right)
     def infixExp(self):  # inorder traversal of expression tree give infix expression
         self.inorder(self.root)
         print()
 if __name__ == "__main__":
     postfixExp = "ab+ef*g*-"
     et = exp_tree(postfixExp)
     et.infixExp() 

Output:

a + b - e * f * g

Related Topics

DAA: KMP Algorithm

KMP ALGORITHM The KMP algorithm is abbreviated as the "Knuth Morris Pratt” algorithm. This algorithm was developed by all of them.  This algorithm searches a pattern of length m in a string...

10 minutes read.

DAA: Algorithm to Find the Maximum Width of a Tree

Algorithm to Find the Maximum Width of a Tree The width of a binary tree is defined as the maximum number of nodes at a given level. The level having the...

5 minutes read.

DAA: Algorithm of Right View of a Binary Tree

Algorithm of Right View of a Binary Tree The right view of a binary tree is the visible nodes from the right side of the tree. In the given tree, the visible...

5 minutes read.

DAA: Dynamic Programming

Dynamic Programming Introduction The technique of breaking a problem statement into subproblems and using the optimal result of subproblems as an optimal result of the problem statement is known as dynamic programming....

2 minutes read.

Invert Binary Tree in DAA

Invert Binary Tree: A binary tree is a tree in which each node of the tree contains two children, i.e., left children and right children. Let us suppose we have...

2 minutes read.

DAA: Floyd Cycle Detection

Floyd Cycle Detection Floyd Cycle algorithm is one of the cycle detection algorithms to detect the cycle in a given singly linked list. In the Floyd Cycle algorithm, we have two pointers...

4 minutes read.

Symmetric Trees in DAA

Symmetric Trees The trees that are mirror images of themselves are known as symmetric trees. Look at the following tree image below: The tree is symmetric as the left subtree is the mirror...

4 minutes read.

DAA: Bead Sort Algorithm

Bead Sort Algorithm The bead sort is also known as the gravity sort algorithm. The algorithm is based on the natural phenomena of gravity. The phenomenon is the falling of things...

3 minutes read.

DAA: Binary Tree and its Categories

Binary Tree and its Categories The binary tree is a non-linear data structure in which there are 0 or utmost 2 nodes.  Each node has two children, i.e., left and right...

4 minutes read.

DAA: Density of a Binary Tree Algorithm

The Density of a Binary Tree Algorithm The density of a binary tree is defined as the ratio of the tree’s size to the tree’s height.  The height of the tree is...

2 minutes read.

DAA: Find the Height or Maximum Depth of a Binary Tree

Find the Height or Maximum Depth of a Binary Tree We have a binary tree structure and we need to find its height. It is defined by the distance from the...

3 minutes read.

Segregate the given Linked List in DAA

Segregate Even and Odd Nodes in a Linked List A linked list is a linear data structure in which each node has two blocks. One contains the node’s value or data,...

3 minutes read.

Recurrence relation in DAA

Recurrence relation in DAA The model that uses mathematical concepts to calculate the time complexity of an algorithm is known as the recurrence relational model. A recursive relation, T(n), is a recursive...

5 minutes read.

Boyer Moore Algorithm

Boyer Moore Algorithm The Boyer Moore algorithm is a searching algorithm in which a string of length n and a pattern of length m is searched. It prints all the occurrences...

11 minutes read.

DAA: Rabin Karp Algorithm

Rabin Karp Algorithm The Rabin Karp or Karp Rabin algorithm is used to matching a specific pattern in the string. It uses the technique of hashing to match a specific text. There also...

6 minutes read.

Introduction to Sorting in DAA

DAA: What is Sorting? The technique in which a data structure is rearranged in decreasing order, increasing order, or in a specified order is called sorting. We apply to sort in our...

4 minutes read.

DAA: Breadth First Search (BFS) for a Graph

Breadth First Search (Bfs) For A Graph The algorithm in which all the graph nodes are traversed is known as the breadth-first search algorithm. In this algorithm, we select one node,...

5 minutes read.

DAA: Application of DFS and BFS

Application of DFS and BFS Depth-first search and breadth-first searches are the most famous algorithms used in daily life and the programming world. Let us now explore each application in which...

3 minutes read.

DAA: Construct a Tree from Inorder and Preorder Traversals

Construct a Tree from Inorder and Preorder Traversals We are given inorder and preorder traversals of a tree. We need to generate a tree from these traversals. Example: Inorder[]   = { 3, 1,...

4 minutes read.

DAA: Bubble Sort Algorithm on Linked List

Bubble Sort Algorithm on Linked List In this article, we will sort a Link List using the bubble sort technique. Example: Input : 20->30->40->10 Output :10->20->30->40 Input : 20->4->3 Output : 3->4->20 Sorting Technique The bubble sort technique...

4 minutes read.