Python Program to Construct an Expression Tree of a given Expression

PythonServer Side ProgrammingProgramming

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

Example: 4 + ((7 + 9) * 2) will have an expression tree like -

Approach to solve this Problem

In order to construct an Expression Tree for a given expression, we generally use Stack Data Structure. Initially we Iterate over the given postfix expression and follow the steps as given below -

  • If we get an operand in the given expression, then push it in the stack. It will become the root of the expression Tree.
  • If an operator gets two values in the expression, then add in the expression tree as its child, and push them in the current node.
  • Repeat Step-1 and Step-2 until we don't complete over our given expression.


Live Demo

class stack:
   def __init__(self):
      self.arr = []
   def push(self, data):
   def pop(self):
         return self.arr.pop(-1)
   def top(self):
         return self.arr[-1]
   def size(self):
      return len(self.arr)
# node class for expression tree
class node:
   def __init__(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
   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
      # travel on rest of the postfix expression
      for i in "".join(reversed(exp[:-1])):
         curr_node =
         if not curr_node.right:
            # if right node of current node is NULL
            temp = node(i)
            curr_node.right = temp
            if self.isOperator(i):
         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):
   def inorder(self, head):
      # inorder traversal of expression tree
      # inorder traversal = > left, root, right
      if head.left:
      print(, end=" ")
      if head.right:
   def infixExp(self):
      # inorder traversal of expression tree give infix expression
if __name__ == "__main__":
   postfixExp = "ab ef*g*-"
   et = exp_tree(postfixExp)

Running the above code will generate the output as,


(a + b - e * f * g)


Constructing a tree from a given expression will generate the output such that the operand will become the root of the node and the rest of the numbers will become the child nodes of the expression tree.

Published on 23-Feb-2021 10:08:05