Question

In: Computer Science

Assignment #2 (JAVA) In assignment 1 you had used the data structure called Stack to evaluate...

Assignment #2 (JAVA)

In assignment 1 you had used the data structure called Stack to evaluate arithmetic expressions by first converting the given infixed expressions to postfixed expressions, and then evaluated the post fixed expression. Repeat the exercise for this assignment (assignment 2) by using the data structure called Binary Trees.

Your output must display the original expression, the postfixed expression representing the Binary tree, and the evaluated result. Please bear in mind that 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 Information regarding

Assignment 1 original expression

class RPN {

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

for (int i = 0; i < s.length; i++) {

Arithmetic a = new Arithmetic(s[i]);

if (a.isBalance()) { System.out.println("Expression " + s[i] + " is balanced\n");
a.postfixExpression();

System.out.println("The post fixed expression is " + a.getPostfix()); a.evaluateRPN();
a.evaluateRPN();

System.out.println("Result of this expression = "+a.getResult());

}else{

System.out.println("Expression is not balanced\n");

}

}

}

}

Solutions

Expert Solution

public class BinaryTree {
    private class Node {
        private char contents;   // either an arithmetic operator or a..z
        private Node left;       // left child
        private Node right;      // right child
        
        /* 
         * isLeaf() - is the specified node a leaf node? 
         */
        private boolean isLeaf() {
            return (left == null && right == null);
        }
    }
    
    private Node root;
    private Scanner in;
    
    public BinaryTree() {
        root = null;
        in = new Scanner(System.in);
    }
/**
     * postorderPrint - uses postfix notation to print the expression tree.
     * It calls postorderPrintTree to perform a recursive postorder traversal.
     */
    public void postorderPrint() {
        if (root != null) {
            postorderPrintTree(root, 0);
        }
    }
    
    /*
     * postorderPrintTree - uses postfix notation to print the
     * expression tree that has the specified node as its root.  It
     * prints the tree by performing a recursive postorder traversal.
     * The margin argument helps to align the output properly.
     */
    private static void postorderPrintTree(Node root, int margin) {
        if (root.isLeaf()) {
            printMargin(margin);
            System.out.print(root.contents + "  ");
        } else {
            postorderPrintTree(root.left, margin + 1);
            postorderPrintTree(root.right, margin + 1);
            
         }
    }
public void read() {
        root = readTree();
    }
private Node readTree() {
        Node n = new Node();
        
        // get next non-whitespace char
        char ch = in.findInLine("(\\S)").charAt(0);
        if ((ch >= 'a') && (ch <='z')) {
            // leaf node
            n.contents = ch;
            n.left = null;
            n.right = null;
        } else if (ch == '(') {
            // an expression
            n.left = readTree();
            n.contents = in.findInLine("(\\S)").charAt(0);
            n.right = readTree();
            ch = in.findInLine("(\\S)").charAt(0);
            if (ch != ')') {
                System.out.print("EXPECTED ) - } ASSUMED...");
            }
        } else {
            System.out.print("EXPECTED ( - CAN'T PARSE");
            System.exit(1);
        }
        
        return n;
    }
    
public static void main(String[] args) {
        // Read in the expression and build the tree.
        System.out.println("\nType a fully parenthesized expression " +
                           "using a..z,+,-,*,/");
        
        BinaryTree tree = new BinaryTree();
        tree.read();
        System.out.print("\n\n* POSTFIX NOTATION:");
        tree.postorderPrint();
        System.out.println();
    }
}

Related Solutions

In assignment 1 you had used the data structure called Stack to evaluate arithmetic expressions by...
In assignment 1 you had used the data structure called Stack to evaluate arithmetic expressions by first converting the given infixed expressions to postfixed expressions, and then evaluated the post fixed expression. Repeat the exercise for this assignment (assignment 2) by using the data structure called Binary Trees. Your output must display the original expression, the postfixed expression representing the Binary tree, and the evaluated result. Please bear in mind that a given expression could result in one of the...
Introduced to data structure using java 2)One of the applications of stack is to convert infix...
Introduced to data structure using java 2)One of the applications of stack is to convert infix expressions to postfix. Given the following infix expression, use the stack method to convert it to postfix. Show your work. x - y / (a + b) + z 3)write a generic method to find the maximum of three variables of generic type (i.e. type T). Note that you must use the compareTo method to compare the values. Also, the code must return one...
0. Introduction. In this assignment you will implement a stack as a Java class, using a...
0. Introduction. In this assignment you will implement a stack as a Java class, using a linked list of nodes. Unlike the stack discussed in the lectures, however, your stack will be designed to efficiently handle repeated pushes of the same element. This shows that there are often many different ways to design the same data structure, and that a data structure should be designed for an anticipated pattern of use. 1. Theory. The most obvious way to represent a...
1. Implement the stack abstract data type. Write it as a separate class called Stack. For...
1. Implement the stack abstract data type. Write it as a separate class called Stack. For simplicity the data type to be stored in the stack is String but you can also use generic type. 2. Test your class implementation by calling push() and pop(). If the stack is empty (size equals zero) pop() should return null and print that “stack is empty”. If stack is full (size equals max) push() returns false and prints that “stack is full”. This...
Java code for creating an Inventory Management System of any company - designing the data structure(stack,...
Java code for creating an Inventory Management System of any company - designing the data structure(stack, queue, list, sort list, array, array list or linked list) (be flexible for future company growth Java code for creating an initial list in a structure. Use Array (or ArrayList) or Linkedlist structure whichever you are confident to use. - Implement Stack, Queue, List type structure and proper operation for your application. Do not use any database. All data must use your data structures....
Discuss the stack data structure. What is it? How can it be used? What support exists...
Discuss the stack data structure. What is it? How can it be used? What support exists for stacks in the Java Class Library Collections Framework? Do you think this support is easy to understand and use? Why or why not? Discuss the pros and cons of creating your own stack classes vs. using those provided by the Java Class Library Collections Framework. Make sure you take into consideration the ability to handle any kind of objects (generics).
This laboratory assignment involves implementing a data structure called a map. A map associates objects called...
This laboratory assignment involves implementing a data structure called a map. A map associates objects called keys with other objects called values. It is implemented as a Java class that uses arrays internally. 1. Theory. A map is a set of key-value pairs. Each key is said to be associated with its corresponding value, so there is at most one pair in the set with a given key. You can perform the following operations on maps. You can test if...
Exercise 3: Stack Write a program in Java to manipulate a Stack List: 1. Create Stack...
Exercise 3: Stack Write a program in Java to manipulate a Stack List: 1. Create Stack List 2. Display the list 3. Create the function isEmply 4. Count the number of nodes 5. Insert a new node in the Stack List. 6. Delete the node in the Stack List. 7. Call all methods above in main method with the following data: Test Data : Input the number of nodes : 4 Input data for node 1 : 5 Input data...
For Part 2 of this assignment, you will use the “Assignment 1 – Linear Kinematics Data”...
For Part 2 of this assignment, you will use the “Assignment 1 – Linear Kinematics Data” excel file. In the data set you are provided with vertical position and time data for a person’s vertical center of mass motion for an unspecified movement task. You will utilize excel in all (well, some…) of its glory to calculate the vertical velocity and vertical acceleration data from the position and time data provided in the excel file. Again you will use the...
please in java ! Assume you have a stack of integers. The stack contains same number...
please in java ! Assume you have a stack of integers. The stack contains same number of positive and negative integers. You want to organize it such that negative and positive integers alternate (+-+-.., or -+-+,..). A. Write a Java code that uses no more than two additional Stacks to solve the problem. Note: You do not need to write the code for Stacks, you are using a Stack from the library with a name ourStack and has the following...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT