Question

Java construct an expression tree, then print the preorder of the tree for each expression Test...

Java

construct an expression tree, then print the preorder of the tree for each expression

Test following cases:

7 * ( 3 - 6 ) + 5 => + * 7 - 3 6 5 13.0 +

18 / -4 => + 13.0 / 18 -4

0.11 / 5 * ( 0.2 * 7 ) => * / 0.11 5 * 0.2 7

-0.27 * 2.21 + 3 - -0.7 / -2

2.05 - 5 + 3 -3 - 1 + 2 + -3.4 / 5

( 855 / 11 ) * ( 12.2 / 321 - ( 1 + 2 + ( 1 + 1.1 + ( 12.51 - 0.51 ) ) ) ) - 0.11

-0.12 + 1.22 - -12.1 / 2.1 => - + -0.12 1.22 / -12.1 2.1

0.5 * 8 / ( 12 + 5 * ( 2 + 3 / 2 ) ) - ( 5 + 1 ) * 3 / 2.5 ==> - / * 0.5 8 + 12 * 5 + 2 / 3 2 / * + 5 1 3 2.5

( -5 + 2 ) / -3 * 2 - -1 / 3 * ( ( 5 / -2) + 1.5 ) => - * / + -5 2 -3 2 * / -1 3 + / 5 -2 1.5

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Program

import java.util.ArrayList;
import java.util.*;

//Stack class
class Stack<T>
{
   //ArratList
   ArrayList<T> stackTop;

   //constructor
   public Stack()
{
stackTop = new ArrayList<>();
}
  
//method to determine whether the stack is empty.
public boolean isEmpty()
{
if(stackTop.isEmpty())
return true;
return false;
}
  
//method to add newItem to the stack.
public void add(T value)
{
stackTop.add(value);
}
  
//method to remove the top element of the stack.
public T pop()
{
if(!isEmpty())
{
        T value = stackTop.get(stackTop.size()-1);
        stackTop.remove(stackTop.size() - 1);
        return value;
}
else
        return null;
}
  
//method to return the top element of the stack.
public T top()
{
   if(!isEmpty())
       return stackTop.get(stackTop.size()-1);
    else
        return null;
}
}

//InfixToPostfix
class InfixToPostfix
{
   //method to return priority of a operator
   public int getPriority(String c)
   {
       switch(c)
       {
           case "^": return 5;
           case "/": return 4;
           case "*": return 3;
           case "+": return 2;
           case "-": return 1;
           case "(": return 0;
          
           default: return 999;
       }
   }
   //check if operator
   boolean isOperator(String s)
   {
       switch(s)
       {
           case "+": case "-": case "/": case "*": case "^":
               return true;
       }
       return false;
   }
  
   //main method
   public String infixToPostfix(String e)
   {
       Stack<String> stk = new Stack();
       String output = "";
      
       stk.add("(");
      
       String exp = e + " )";
      
       String arr[] = exp.split(" ", 50);
      
       //convert from infix to postfix
       for(int i=0; i<arr.length; i++)
       {
           String ch = arr[i];
                                  
           //check for left parenthesis
           if(ch.equals("("))
           {
               stk.add(ch);
           }
           //check for righr parenthesis
           else if(ch.equals(")"))
           {
               while(!stk.top().equals("("))
               {
                   output = output + stk.pop() + " ";
                  
               }
               stk.pop();
           }
           //operator
           else if(isOperator(ch))
           {
               int p1 = getPriority(ch);
      
               int p2 = getPriority(stk.top());
              
               while(p1<=p2)
               {  
                   output = output + stk.pop() + " ";
                   p2 = getPriority(stk.top());
               }
               stk.add(ch);
           }
           //operand
           else
           {
               output = output + ch + " ";
           }
       //   System.out.println (output);
          
       }
  
      
       if(!stk.isEmpty())
           return "None";
       else
           return output;
   }
}

//Node class
class Node
{
   String info;
   Node lchild;
   Node rchild;
  
   //constructor
   Node(String val)
   {
       info = val;
       lchild = null;
       rchild = null;
   }
}

//ExpressionTree class
class ExpressionTree
{
   //check for operator
   boolean isOperator(String s)
   {
       switch(s)
       {
           case "+": case "-": case "/": case "*": case "^":
               return true;
       }
       return false;
   }
  
   //preorder traversal
   void preorder(Node root)
   {
       if(root!=null)
       {
           System.out.print(root.info + " ");
           preorder(root.lchild);
           preorder(root.rchild);
       }
   }
  
   //expression tree construction
   Node expressionTreeConstruction(String postfix)
   {
       Stack<Node> stk = new Stack();
      
       String arr[] = postfix.split(" ",20);
      
       Node t = null;
      
       for(int i=0; i<arr.length-1; i++)
       {
           if(arr[i]==" ") continue;
           t = new Node(arr[i]);
           if(!isOperator(arr[i]))
           {
               stk.add(t);
           }
           else
           {
               Node r = stk.pop();
               Node l = stk.pop();
               t.lchild = l;
               t.rchild = r;
               stk.add(t);
           }
       }

       return stk.pop();
   }
  
   //main method
   public static void main (String[] args)
   {
       Scanner sc = new Scanner(System.in);
      
       System.out.println("Enter the expression: ");
       String infix = sc.nextLine();
      
       InfixToPostfix ip = new InfixToPostfix();
       String postfix = ip.infixToPostfix(infix);
      
       //System.out.println("Postfix Expression: " + postfix);
      
       if(postfix.equals("None"))
       {
           System.out.println("Invalid expession");
           return;
       }
          
       ExpressionTree etree = new ExpressionTree();
       Node root = etree.expressionTreeConstruction(postfix);
      
       System.out.println("Preorder traversal of the Expression Tree: ");
       etree.preorder(root);
   }
}

Output:

Enter the expression:
7 * ( 3 - 6 ) + 5
Preorder traversal of the Expression Tree:
+ * 7 - 3 6 5

Enter the expression:
13.0 + 18 / -4
Preorder traversal of the Expression Tree:
+ 13.0 / 18 -4

Enter the expression:
0.11 / 5 * ( 0.2 * 7 )
Preorder traversal of the Expression Tree:
* / 0.11 5 * 0.2 7

Enter the expression:
( -5 + 2 ) / -3 * 2 - -1 / 3 * ( ( 5 / -2 ) + 1.5 )
Preorder traversal of the Expression Tree:
- * / + -5 2 -3 2 * / -1 3 + / 5 -2 1.5

Add a comment
Know the answer?
Add Answer to:
Java construct an expression tree, then print the preorder of the tree for each expression Test...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT