Java Program to Implement Expression Tree

This is a Java Program to implement Expression Tree. Expression Tree is used in evaluating expressions.

Here is the source code of the Java program to implement Expression Tree. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. /**
  2.  * Java Program to Implement Expression Tree Algorithm
  3.  */
  4.  
  5. import java.util.Scanner;
  6.  
  7. /** Class ExpressionTree **/
  8. class ExpressionTree
  9. {
  10.     /** class TreeNode **/
  11.     class TreeNode
  12.     {    
  13.         char data;
  14.         TreeNode left, right;
  15.  
  16.         /** constructor **/
  17.         public TreeNode(char data)
  18.         {
  19.             this.data = data;
  20.             this.left = null;
  21.             this.right = null;
  22.         }
  23.     } 
  24.  
  25.     /** class StackNode **/
  26.     class StackNode
  27.     {
  28.         TreeNode treeNode;
  29.         StackNode next;
  30.  
  31.         /** constructor **/
  32.         public StackNode(TreeNode treeNode)
  33.         {
  34.             this.treeNode = treeNode;
  35.             next = null;
  36.         }
  37.     }
  38.  
  39.     private static StackNode top;
  40.  
  41.     /** constructor **/
  42.     public ExpressionTree()
  43.     {
  44.         top = null;
  45.     }
  46.  
  47.     /** function to clear tree **/
  48.     public void clear()
  49.     {
  50.         top = null;
  51.     }
  52.  
  53.     /** function to push a node **/
  54.     private void push(TreeNode ptr)
  55.     {
  56.         if (top == null)
  57.             top = new StackNode(ptr);
  58.         else
  59.         {
  60.             StackNode nptr = new StackNode(ptr);
  61.             nptr.next = top;
  62.             top = nptr;
  63.         }
  64.     }
  65.  
  66.     /** function to pop a node **/
  67.     private TreeNode pop()
  68.     {
  69.         if (top == null)
  70.             throw new RuntimeException("Underflow");
  71.         else
  72.         {
  73.             TreeNode ptr = top.treeNode;
  74.             top = top.next;
  75.             return ptr;
  76.         }
  77.     }
  78.  
  79.     /** function to get top node **/
  80.     private TreeNode peek()
  81.     {
  82.         return top.treeNode;
  83.     }
  84.  
  85.     /** function to insert character **/
  86.     private void insert(char val)
  87.     {
  88.         try
  89.         {
  90.             if (isDigit(val))
  91.             {
  92.                 TreeNode nptr = new TreeNode(val);
  93.                 push(nptr);
  94.             }
  95.             else if (isOperator(val))
  96.             {
  97.                 TreeNode nptr = new TreeNode(val);
  98.                 nptr.left = pop();
  99.                 nptr.right = pop();
  100.                 push(nptr);
  101.             }
  102.         }
  103.         catch (Exception e)
  104.         {
  105.             System.out.println("Invalid Expression");
  106.         }
  107.     }
  108.  
  109.     /** function to check if digit **/
  110.     private boolean isDigit(char ch)
  111.     {
  112.         return ch >= '0' && ch <= '9';
  113.     }
  114.  
  115.     /** function to check if operator **/
  116.     private boolean isOperator(char ch)
  117.     {
  118.         return ch == '+' || ch == '-' || ch == '*' || ch == '/';
  119.     }
  120.  
  121.     /** function to convert character to digit **/
  122.     private int toDigit(char ch)
  123.     {
  124.         return ch - '0';
  125.     }
  126.  
  127.     /** function to build tree from input */
  128.     public void buildTree(String eqn)
  129.     {
  130.         for (int i = eqn.length() - 1; i >= 0; i--)
  131.             insert(eqn.charAt(i));
  132.     }
  133.  
  134.     /** function to evaluate tree */
  135.     public double evaluate()
  136.     {
  137.         return evaluate(peek());
  138.     }
  139.  
  140.     /** function to evaluate tree */
  141.     public double evaluate(TreeNode ptr)
  142.     {
  143.         if (ptr.left == null && ptr.right == null)
  144.             return toDigit(ptr.data);
  145.         else
  146.         {
  147.             double result = 0.0;
  148.             double left = evaluate(ptr.left);
  149.             double right = evaluate(ptr.right);
  150.             char operator = ptr.data;
  151.  
  152.             switch (operator)
  153.             {
  154.             case '+' : result = left + right; break;
  155.             case '-' : result = left - right; break;
  156.             case '*' : result = left * right; break;
  157.             case '/' : result = left / right; break;
  158.             default  : result = left + right; break;
  159.             }
  160.             return result;
  161.         }
  162.     }
  163.  
  164.     /** function to get postfix expression */
  165.     public void postfix()
  166.     {
  167.         postOrder(peek());
  168.     }
  169.  
  170.     /** post order traversal */
  171.     private void postOrder(TreeNode ptr)
  172.     {
  173.         if (ptr != null)
  174.         {
  175.             postOrder(ptr.left);            
  176.             postOrder(ptr.right);
  177.             System.out.print(ptr.data);            
  178.         }    
  179.     }
  180.  
  181.     /** function to get infix expression */
  182.     public void infix()
  183.     {
  184.         inOrder(peek());
  185.     }
  186.  
  187.     /** in order traversal */
  188.     private void inOrder(TreeNode ptr)
  189.     {
  190.         if (ptr != null)
  191.         {
  192.             inOrder(ptr.left);
  193.             System.out.print(ptr.data);
  194.             inOrder(ptr.right);            
  195.         }    
  196.     }
  197.  
  198.     /** function to get prefix expression */
  199.     public void prefix()
  200.     {
  201.         preOrder(peek());
  202.     }
  203.  
  204.     /** pre order traversal */
  205.     private void preOrder(TreeNode ptr)
  206.     {
  207.         if (ptr != null)
  208.         {
  209.             System.out.print(ptr.data);
  210.             preOrder(ptr.left);
  211.             preOrder(ptr.right);            
  212.         }    
  213.     }
  214. }
  215.  
  216. /** class ExpressionTreeTest **/
  217. public class ExpressionTreeTest
  218. {
  219.     public static void main(String[] args)
  220.     {
  221.         Scanner scan = new Scanner(System.in);
  222.         System.out.println("Expression Tree Test");
  223.  
  224.         /** make object of ExpressionTree **/
  225.         ExpressionTree et = new ExpressionTree();
  226.  
  227.         System.out.println("\nEnter equation in prefix form");
  228.         et.buildTree(scan.next());
  229.  
  230.         System.out.print("\nPrefix  : ");
  231.         et.prefix();
  232.         System.out.print("\n\nInfix   : ");
  233.         et.infix();
  234.         System.out.print("\n\nPostfix : ");
  235.         et.postfix();
  236.         System.out.println("\n\nEvaluated Result : "+ et.evaluate());
  237.     }
  238. }

Expression Tree Test
 
Enter equation in prefix form
+-+7*/935/82*/625
 
Prefix  : +-+7*/935/82*/625
 
Infix   : 7+9/3*5-8/2+6/2*5
 
Postfix : 793/5*+82/-62/5*+
 
Evaluated Result : 33.0

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.