Question

Create a program using Binary Trees in Java to do the following 1. Verify a given...

Create a program using Binary Trees in Java to do the following

1. Verify a given expression is balanced in regards to parentheses

2. covert an infix expression to a postfix expression

3. Evaluate the expression

Given expressions:

String s[] = {"5 + ) * ( 2",
" 2 + ( - 3 * 5 ) ",
"(( 2 + 3 ) * 5 ) * 8 ",
"5 * 10 + ( 15 - 20 ) ) - 25",
" 5 + ( 5 * 10 + ( 15 - 20 ) - 25 ) * 9"
};

a given expression could result in one of the following:

Mismatch parentheses
Too many operators, or too many operands in which case the expression would not have been written properly in the first place
The result is assumed to be correct.

Homework Answers

Answer #1


package expressiontree.java;

public class ExpressionTree {
String data;
ExpressionTree left;
ExpressionTree right;
boolean bracmismatch;
boolean opermismatch;
ExpressionTree()
{
data="";
left=null;
right=null;
bracmismatch=false;
opermismatch=false;
  
}
ExpressionTree(String val)
{
data=val;
left=null;
right=null;
bracmismatch=false;
opermismatch=false;
  
}
boolean isOperator(char ch)
{
String operators="+-/*%";
return operators.indexOf(ch)>-1;
}
ExpressionTree NodeInsert(String exp)
{
  
ExpressionTree node=new ExpressionTree();
String operand="";
node.left=null;
node.right=null;
int brac_count;
int i;
for(i=0;i<exp.length();i++)
{
if(isOperator(exp.charAt(i)))
{
if((i>=0)&&((i+1)<exp.length()))
{
  
node.left=NodeInsert(exp.substring(0,i));
operand=""+exp.charAt(i);
  
  
//IF NEGATIVE VALUES ARE ACCEPTED
if((node.left==null)&&(operand.equals("-")))
{
i=i+1;
while((i<exp.length())&&(!isOperator(exp.charAt(i))))
{
operand+=exp.charAt(i);
i++;
}
  
node.left=new ExpressionTree(operand);
if(i<exp.length())
{
operand=""+exp.charAt(i);
node.right=NodeInsert(exp.substring(i+1));
}
  
}
else
{
node.right=NodeInsert(exp.substring(i+1));
}
  
//IF ONLY POSITIVE VALUES ARE ACCEPTED
/*

node.right=NodeInsert(exp.substring(i+1));

if((node.left==null)||(node.right==null))
{
  
node.opermismatch=true;
  
}*/

  
//IF NEGATIVE VALUES ARE ACCEPTED
if(((node.left==null)||(node.right==null))&&(!operand.equals("-")))
{
node.opermismatch=true;
}
if((node.right==null)&&(operand.equals("-")))
{
node.opermismatch=true;
  
}
  
  
break;
}
  
}
else if(exp.charAt(i)=='(')
{
brac_count=1;
int j=i+1;
while(j<exp.length()&&(brac_count>0))
{
if((exp.charAt(j)=='('))
{
brac_count++;
}
else if(((exp.charAt(j)==')')))
{
brac_count--;
}
j++;
}   
if((i==0)&&(j==exp.length()))
{
exp=exp.substring(i+1,j-1);
return (NodeInsert(exp));
}
if(j==exp.length())
node.bracmismatch=true;
i=j-1;
}
else if(exp.charAt(i)==')')
{
node.bracmismatch=true;
}
  
else
operand=operand+exp.charAt(i);
  
}
if("".equals(operand))return null;
node.data=operand;
return node;
}
void printPost(ExpressionTree head)
{
if(head.left!=null)
printPost(head.left);
if(head.right!=null)
printPost(head.right);
  
System.out.print(head.data+"\t");
}
boolean checkOper(ExpressionTree head)
{
boolean flag=false;
if(head.opermismatch==true)
{
return head.opermismatch;
}
if(head.left!=null)
{
flag=checkOper(head.left);
}
if(flag==true)
{
return flag;
}
if(head.right!=null)
{
flag=checkOper(head.right);
}
  
return flag;
}
boolean checkBrac(ExpressionTree head)
{
boolean flag=false;
if(head.bracmismatch==true)
{
return head.bracmismatch;
}
if(head.left!=null)
{
flag=checkBrac(head.left);
}
if(flag==true)
{
return flag;
}
if(head.right!=null)
{
flag=checkBrac(head.right);
}
  
return flag;
}
public static void main(String[] args) {

String s[] = {"5+)*(2","2+(-3*5)","((2+3)*5)*8","5*10+(15-20))-25","5+(5*10+(15-20)-25)*9"};
for (String expression : s) {
System.out.println(expression);
ExpressionTree exptree=new ExpressionTree();
exptree=exptree.NodeInsert(expression);
if(exptree.checkBrac(exptree))
{
System.out.println("Mismatch parentheses");
}
else if(exptree.checkOper(exptree))
{
System.out.println("Too many operators, or too many operands in which case the expression would not have been written properly in the first place");
}
else
{
System.out.print("The result is assumed to be correct.");
exptree.printPost(exptree);
System.out.println();
}
}

}
  
}

OUTPUT:(Neg values accepted)

OUTPUT:(Neg values not accepted)

With Evaluation:

package expressiontree;

import java.util.Stack;
import javafx.util.Pair;

public class ExpressionTree {
String data;
ExpressionTree left;
ExpressionTree right;
boolean bracmismatch;
boolean opermismatch;
static Stack<Integer> stack=new Stack<>();
static Pair prec[]=new Pair[5];
ExpressionTree()
{
data="";
left=null;
right=null;
bracmismatch=false;
opermismatch=false;
prec[0]=new Pair('+',0);
prec[1]=new Pair('-',0);
prec[2]=new Pair('*',1);
prec[3]=new Pair('/',1);
  
}
static int getVal(char c)
{
int val=-1;
for(int i=0;i<4;i++)
{
if((char)prec[i].getKey()==c)
{
val=(int)prec[i].getValue();
break;
}
}
return val;
}
ExpressionTree(String val)
{
data=val;
left=null;
right=null;
bracmismatch=false;
opermismatch=false;
  
}
boolean isOperator(char ch)
{
String operators="+-/*%";
return operators.indexOf(ch)>-1;
}
ExpressionTree NodeInsert(String exp,int prec)
{
  
ExpressionTree node=new ExpressionTree();
String operand="";
node.left=null;
node.right=null;
int brac_count;
int i;
  
for(i=0;i<exp.length();i++)
{

if(isOperator(exp.charAt(i))&&(prec<=getVal(exp.charAt(i))))
{
if((i>=0)&&((i+1)<exp.length()))
{

node.left=NodeInsert(exp.substring(0,i),0);
operand=""+exp.charAt(i);
  
  
/*//IF NEGATIVE VALUES ARE ACCEPTED
if((node.left==null)&&(operand.equals("-")))
{
i=i+1;
while((i<exp.length())&&(!isOperator(exp.charAt(i))))
{
operand+=exp.charAt(i);
i++;
}
  
node.left=new ExpressionTree(operand);
if(i<exp.length())
{
operand=""+exp.charAt(i);
node.right=NodeInsert(exp.substring(i+1));
}
  
}
else
{
node.right=NodeInsert(exp.substring(i+1));
}*/
  
//IF ONLY POSITIVE VALUES ARE ACCEPTED
//System.out.println(exp.substring(i+1));
node.right=NodeInsert(exp.substring(i+1),getVal(exp.charAt(i)));
if((node.left==null)||(node.right==null))
{
  
node.opermismatch=true;
  
}
  
if(getVal(exp.charAt(i))==1){

  
i++;
while((!isOperator(exp.charAt(i)))&&(i+1<exp.length())&&(exp.charAt(i)!=')'))
{
i++;
  
}
  
if(i+1!=exp.length())
{
ExpressionTree innernode=new ExpressionTree();
innernode.left=node ;
node.data=operand;
innernode.right=NodeInsert(exp.substring(i+1),0);
node=innernode;
operand=""+exp.charAt(i);
}
}
  
/*//IF NEGATIVE VALUES ARE ACCEPTED
if(((node.left==null)||(node.right==null))&&(!operand.equals("-")))
{
node.opermismatch=true;
}
if((node.right==null)&&(operand.equals("-")))
{
node.opermismatch=true;
  
}*/
  
  
break;
}
  
}
else if(exp.charAt(i)=='(')
{
brac_count=1;
int j=i+1;
while(j<exp.length()&&(brac_count>0))
{
if((exp.charAt(j)=='('))
{
brac_count++;
}
else if(((exp.charAt(j)==')')))
{
brac_count--;
}
j++;
}   
if((i==0)&&(j==exp.length()))
{
exp=exp.substring(i+1,j-1);
return (NodeInsert(exp,0));
}
if(j==exp.length())
node.bracmismatch=true;
i=j-1;
}
else if(exp.charAt(i)==')')
{
node.bracmismatch=true;
}
else if(isOperator(exp.charAt(i))&&(prec>getVal(exp.charAt(i))))
{
return NodeInsert(exp.substring(0,i),0);
}
else
operand=operand+exp.charAt(i);
  
}
if("".equals(operand))return null;
node.data=operand;
return node;
}
void printPost(ExpressionTree head)
{
if(head.left!=null)
printPost(head.left);
if(head.right!=null)
printPost(head.right);
try{
stack.push(Integer.parseInt(head.data));
}
catch(Exception e)
{

int v1 = stack.pop();
int v2 = stack.pop();
  
switch(head.data)
{
case "+":
stack.push(v2+v1);
break;
  
case "-":
stack.push(v2- v1);
break;
  
case "/":
stack.push(v2/v1);
break;
  
case "*":
stack.push(v2*v1);
break;
}
  
}
System.out.print(head.data+"\t");
}
  
boolean checkOper(ExpressionTree head)
{
boolean flag=false;
if(head.opermismatch==true)
{
return head.opermismatch;
}
if(head.left!=null)
{
flag=checkOper(head.left);
}
if(flag==true)
{
return flag;
}
if(head.right!=null)
{
flag=checkOper(head.right);
}
  
return flag;
}
boolean checkBrac(ExpressionTree head)
{
boolean flag=false;
if(head.bracmismatch==true)
{
return head.bracmismatch;
}
if(head.left!=null)
{
flag=checkBrac(head.left);
}
if(flag==true)
{
return flag;
}
if(head.right!=null)
{
flag=checkBrac(head.right);
}
  
return flag;
}
public static void main(String[] args) {

String s[] = {"5+)*(2","2+(-3*5)","((2+3)*5)*8","5*10+(15-20))-25","5+(5*10+(15-20)-25)*9"};
for (String expression : s) {
System.out.println(expression);
ExpressionTree exptree=new ExpressionTree();
exptree=exptree.NodeInsert(expression,0);
if(exptree.checkBrac(exptree))
{
System.out.println("Mismatch parentheses");
}
else if(exptree.checkOper(exptree))
{
System.out.println("Too many operators, or too many operands in which case the expression would not have been written properly in the first place");
}
else
{
System.out.print("The result is assumed to be correct.");
exptree.printPost(exptree);
System.out.println();
System.out.println("Result : "+stack.pop());
}
}

}
  
}

Know the answer?
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
Similar Questions
(For Python) Evaluating Postfix Arithmetic Expressions. In this project you are to implement a Postfix Expression...
(For Python) Evaluating Postfix Arithmetic Expressions. In this project you are to implement a Postfix Expression Evaluator as described in section 7-3b of the book. The program should ask the user for a string that contains a Postfix Expression. It should then use the string's split function to create a list with each token in the expression stored as items in the list. Now, using either the stack classes from 7.2 or using the simulated stack functionality available in a...
Problem 1: Write a Java program for traversing a Binary Search Tree in following ways: (use...
Problem 1: Write a Java program for traversing a Binary Search Tree in following ways: (use any data structure, library functions) ---------- 20 points i) Depth First Traversal: Inorder, LVR ii) Depth First Traversal: Inorder, RVL iii) Depth First Traversal: Preorder, VLR iv) Depth First Traversal: Preorder, VRL v) Depth First Traversal: Postorder, LRV vi) Depth First Traversal: Postorder, RLV No choice menu required. Sample Input (taken from keyboard, single space separated nodes as found in a complete BFS: top-down,...
Write a Java program using the OOP paradigm to do the following: 1. Main Function: create...
Write a Java program using the OOP paradigm to do the following: 1. Main Function: create a list with a million items, and you can use the generate function to add a million random values to the list. 2. Create a method to sort the list created in the main function using bubble sort, then use the sorted list to search for the (k) value using binary search. 3. Create a method to create a new list of 1000 items...
Write a Java program to print the result of the following operations. Your program should contain...
Write a Java program to print the result of the following operations. Your program should contain 4 methods (for each of given data sets). Yes, methods here are not structurally necessary, this requirement is only for you to get practice writing methods. Test Data: a. -8 + 4.0 * 6 b. (11+9) % 9 c. 20 + (-3)*3.0 / 8 d. 5 + 14 / 3 * 2 - 7 % 3 Your program:
Make Java program with the following tasks: 1. Create a new database called DTCC 2. Create...
Make Java program with the following tasks: 1. Create a new database called DTCC 2. Create a table called Students in the DTCC database with the following fields:     Student_ID    CHAR (10) ** make sure to set this field as the primary key     LastName      CHAR(20)     FirstName     CHAR(15)     PlanOfStudy CHAR(25)     GPA               Double 3. Insert 5 records into Students table: 899090111    Rothlisberger   Ben          CIT                                       3.7 129020202    Manning          Peyton     Computer Programming       3.8 890101030    Brady               Tom         Accounting                           3.4 980191919    Rodgers           Aaron       Networking                          3.2...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*;...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*; import javax.swing.*; public class Clicker extends JFrame implements ActionListener {     int count;     JButton button;     Clicker() {         super("Click Me");         button = new JButton(String.valueOf(count));         add(button);         button.addActionListener(this);         setSize(200,100);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         setVisible(true);     }     public void actionPerformed(ActionEvent e) {         count++;         button.setText(String.valueOf(count));     }     public static void main(String[] args) { new Clicker(); } } a. add(button);...
Identify errors and correct them of the following Java program: 1. import java.utility.Random; 2. 3. public...
Identify errors and correct them of the following Java program: 1. import java.utility.Random; 2. 3. public class Sequen 4. 5. private int stand 6. private int calc; 7. 8. public Sequen(int numStand) 9. { 10. stand = numStand; 11. skip; 12. } 13. 14. public void skip() 15. { 16. Random sit = new Random(); 17. calc = sit.nextInt(stand) + 1; 18. } 19. 20. public getStand() 21. { 22. return stand; 23. } 24. 25. int getCalc() 26. {...
Identify errors and correct them of the following Java program: 1. import java.utility.Random; 2.   3. public...
Identify errors and correct them of the following Java program: 1. import java.utility.Random; 2.   3. public class Sequen 4.   5. private int stand   6. private int calc;   7.   8. public Sequen(int numStand) 9. { 10.         stand = numStand; 11.         skip; 12.         } 13.           14.         public void skip() 15.         { 16.         Random sit = new Random(); 17.         calc = sit.nextInt(stand) + 1; 18.         } 19.           20.         public getStand() 21.         { 22.         return stand; 23.         } 24.           25.         int getCalc() 26.         { 27.         return calc; 28.         } 29.         } One error is already identified for you as shown below:...
URGENT!!!!!!!!!!!!!!!!!!!!! Identify errors and correct them of the following Java program: 1. import java.utility.Random; 2.   3....
URGENT!!!!!!!!!!!!!!!!!!!!! Identify errors and correct them of the following Java program: 1. import java.utility.Random; 2.   3. public class Sequen 4.   5. private int stand   6. private int calc;   7.   8. public Sequen(int numStand) 9. { 10.         stand = numStand; 11.         skip; 12.         } 13.           14.         public void skip() 15.         { 16.         Random sit = new Random(); 17.         calc = sit.nextInt(stand) + 1; 18.         } 19.           20.         public getStand() 21.         { 22.         return stand; 23.         } 24.           25.         int getCalc() 26.         { 27.         return calc; 28.         } 29.         } One error is already identified for you as shown...
Identify errors and correct them of the following Java program: 1. import java.utility.Random; 2.   3. public...
Identify errors and correct them of the following Java program: 1. import java.utility.Random; 2.   3. public class Sequen 4.   5. private int stand   6. private int calc;   7.   8. public Sequen(int numStand) 9. { 10.         stand = numStand; 11.         skip; 12.         } 13.           14.         public void skip() 15.         { 16.         Random sit = new Random(); 17.         calc = sit.nextInt(stand) + 1; 18.         } 19.           20.         public getStand() 21.         { 22.         return stand; 23.         } 24.           25.         int getCalc() 26.         { 27.         return calc; 28.         } 29.         } One error is already identified for you as shown below:...