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...
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...
In Java or C++, implement a stack and a queue using a linkedlist data structure.  You may...
In Java or C++, implement a stack and a queue using a linkedlist data structure.  You may not use any standard Java or C++ libraries. Assume your data structure only allows Strings. Implement the following operations for the data structure: Queue: enqueue, dequeue, create, isEmpty (10 points) Stack: push, pop, create, isEmpty (10 points) Here is a link to get started on transferring from Java to C++ http://www.horstmann.com/ccj2/ccjapp3.html (Links to an external site.) Upload a zip file with one implementation for...
CS 400 Assignment 4 Stack application: postfix expression evaluation. Description: - The stack data structure can...
CS 400 Assignment 4 Stack application: postfix expression evaluation. Description: - The stack data structure can be used to evaluate postfix expressions. Please refer to the first 14 pages of this tutorial for postfix expression evaluation: http://www.cs.nthu.edu.tw/~wkhon/ds/ds10/tutorial/tutorial2.pdf Requirement: - deal with single digit positive integers only. Operands and operators are fully separated by space. - learn and use STL stack: http://www.cplusplus.com/reference/stack/stack/ - learn and use isdigit(): http://www.cplusplus.com/reference/cctype/isdigit/ - take in a postfix arithmetic expression from cin, and evaluate its value....
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....
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...
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).
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT