Question

Lab 9 You will be inserting values into a generic tree, then printing the values inorder,...

Lab 9

You will be inserting values into a generic tree, then printing the values inorder, as well as printing the minimum and maximum values in the tree. Given main(), write the methods in the 'BSTree' class specified by the // TODO: sections. There are 5 TODOs in all to complete.

Ex: If the input is

like
ferment
bought
tasty
can
making
apples
super
improving
juice
wine
-1

the output should be:

Enter the words on separate lines to insert into the tree, enter -1 to stop

The Elements Inorder: apples - bought - can - ferment - improving - juice - like - making - super - tasty - wine - 

The minimum element in the tree is apples

The maximum element in the tree is wine

Main.java

import java.util.Scanner;

public class Main {

   public static void main(String[] args) {

       BSTree<String> tree = new BSTree<String>();
      
       Scanner scrn = new Scanner(System.in);
       System.out.println("Enter the words on separate lines to insert into the tree, enter -1 to stop");
      
       String word = scrn.nextLine();
       while(!word.equals("-1")) {
           tree.addElement(word);
           word = scrn.nextLine();
       }
       System.out.println();
      
       tree.printElements();
      
       System.out.println("\nThe minimum element in the tree is " + tree.findMin());
       System.out.println("\nThe maximum element in the tree is " + tree.findMax());

   }

}

BSTreeNode.java

public class BSTreeNode<T> {

   private T element;
   private BSTreeNode<T> left, right;

   public BSTreeNode(T element) {
       this.element = element;
       this.left = null;
       this.right = null;
   }

   public T getElement() {
       return element;
   }

   public void setElement(T element) {
       this.element = element;
   }

   public BSTreeNode<T> getLeft() {
       return left;
   }

   public void setLeft(BSTreeNode<T> left) {
       this.left = left;
   }

   public BSTreeNode<T> getRight() {
       return right;
   }

   public void setRight(BSTreeNode<T> right) {
       this.right = right;
   }
      
}

BSTree.java

public class BSTree<T> {

   private BSTreeNode<T> root = null;

   // TODO: Write an addElement method that inserts generic Nodes into
   // the generic tree. You will need to use a Comparable Object

// TODO: write the method printElements
       // It should check that the tree isn't empty
       // and prints "The Tree is empty" if it is
       // otherwise prints "The Elements Inorder: "
       // and calls the inorder method

// TODO: write the inorder method that traverses
       // the generic tree and prints the data inorder

// TODO: write the findMin method that returns the
       // minimum value element in the tree

// TODO: write the findMin method that returns the
       // maximum value element in the tree

Homework Answers

Answer #1

So, here is the solution of the given problem.
I am attaching the well-commented source code along with the Screenshots of the code as well as output.

Source Code:

Main Class is same as question.

compareTo function in BSTreeNode class

 class BSTreeNode<T> {

   private T element;
   private BSTreeNode<T> left, right;

   public BSTreeNode(T element) {
       this.element = element;
       this.left = null;
       this.right = null;
   }

   public T getElement() {
       return element;
   }

   public void setElement(T element) {
       this.element = element;
   }

   public BSTreeNode<T> getLeft() {
       return left;
   }

   public void setLeft(BSTreeNode<T> left) {
       this.left = left;
   }

   public BSTreeNode<T> getRight() {
       return right;
   }

   public void setRight(BSTreeNode<T> right) {
       this.right = right;
   }



   //first convert the element into String then apply compareTo on both Strings
   public int compareTo(BSTreeNode<T> node){
         return String.valueOf(this.getElement()).compareTo( String.valueOf(node.getElement()));
   }
}

BSTree class:

class BSTree<T> {

   private BSTreeNode<T> root = null;

   //addElement function to add element into the BST
   void addElement(T data){ 
        //creating the node to be inserted
       BSTreeNode<T> node = new BSTreeNode(data);
       
       //if root is null that means tree is null so make the node as root
       if(root == null){
           root = node;
           return;
       }
       //else initialize a temp variable with root and ....
       BSTreeNode<T> temp = root;
       
       //while temp is not null
       while(temp != null){

            //if compareTo function return negative number that means node to be inserted is greater than the current node
           if(temp.compareTo(node)<0){
               //if right is null assign the node to its right
                    if(temp.getRight() != null)
                        temp = temp.getRight();
            //else move to the right of current node
                    else{
                        temp.setRight(node);
                        break;
                    }
               
           }
       //if compareTo function return positive number that means node to be inserted is lesser than the current node
            else {
               //if left is null assign the node to its left
             if(temp.getLeft()  != null)
                temp = temp.getLeft();
            //else move to the left of current node
                else{
                    temp.setLeft(node);
                    break;
                }
            }
       }
   }
   

//function to print elements
    void printElements(){

    //if tree is null print statement and return
        if(root == null){
            System.out.println("The Tree is empty");
            return;
        }
//else call inorder 
        inorder(root);
        System.out.println();
    }
    
    
    
    //inorder function
    void inorder(BSTreeNode<T> node){
        if(node == null)
            return;
        inorder(node.getLeft());
        System.out.print(node.getElement() + " - ");
        inorder(node.getRight());
    }


//to find minimum element print the left most node of the tree as we know left most node of BST is always minimum

    T findMin(){
        if(root == null)
            return null;
        BSTreeNode<T> temp = root;
        while(temp != null && temp.getLeft() != null)
            temp = temp.getLeft();
           
    return temp.getElement();
    }
    
    
//to find maximum element print the right most node of the tree as we know right most node of BST is always maximum
           
      T findMax(){
        if(root == null)
            return null;
        BSTreeNode<T> temp = root;
        while(temp != null &&  temp.getRight() != null)
            temp = temp.getRight();
            
    return temp.getElement();
    }
}

Here are the screenshots:

compareTo function:

BSTree class:

Output of the code:

So, this was the solutions of the problem.
I hope I am able to solve your problem, if yes then do give it a like.
It really helps :)

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
Java Program: You will be inserting values into a generic tree, then printing the values inorder,...
Java Program: You will be inserting values into a generic tree, then printing the values inorder, as well as printing the minimum and maximum values in the tree. Given main(), write the methods in the 'BSTree' class specified by the // TODO: sections. There are 5 TODOs in all to complete. Ex: If the input is like ferment bought tasty can making apples super improving juice wine -1 the output should be: Enter the words on separate lines to insert...
You will be traversing through an integer tree to print the data. Given main(), write the...
You will be traversing through an integer tree to print the data. Given main(), write the methods in the 'IntegerBinaryTree' class specified by the // TODO: sections. There are 6 methods in all to write. Ex: If the input is 70 86 60 90 49 62 81 85 38 -1 the output should be: Enter whole numbers to insert into the tree, -1 to stop Inorder: 38 - 49 - 60 - 62 - 70 - 81 - 85 -...
Java Program: You will be traversing through an integer tree to print the data. Given main(),...
Java Program: You will be traversing through an integer tree to print the data. Given main(), write the methods in the 'IntegerBinaryTree' class specified by the // TODO: sections. There are 6 methods in all to write. Ex: If the input is: 70 86 60 90 49 62 81 85 38 -1 the output should be: Enter whole numbers to insert into the tree, -1 to stop Inorder: 38 - 49 - 60 - 62 - 70 - 81 -...
This is my current code and im having trouble inserting the findMin, findMax, and Search functions...
This is my current code and im having trouble inserting the findMin, findMax, and Search functions in main to output them. #include<iostream> using namespace std; /*Define the class for BST*/ class BST_TREE {    /*Structure of the tree*/    struct tree    {        int value;        tree* left;        tree* right;    };    tree* root;    /*Method to clear the tree*/    tree* Empty(tree* t)    {        if (t == NULL)       ...
TrackMinMax For this lab, you will create a generic version of the IntTrackMinMax class you wrote...
TrackMinMax For this lab, you will create a generic version of the IntTrackMinMax class you wrote in a previous lab, called TrackMinMax. The API is: Function Signature Description constructor TrackMinMax() constructor check void check(T i) compares i to the current minimum and maximum values and updates them accordingly getMin T getMin() returns the minimum value provided to check() so far getMax T getMax() returns the maximum value provided to check() so far toString String toString() returns the string "[min,max]" As...
The one missing piece was inserting into a binary search tree; we'll take care of that...
The one missing piece was inserting into a binary search tree; we'll take care of that today and write the insert function, as well as a height function. Both functions will be implemented in the "bst.h" header file, and tested using a provided main program in "main.cpp". Step one is to implement the insert function --- go ahead and modify "bst.h", adding the necessary code to (1) allocate a new node, and (b) link it into the tree. Once you...
(JAVA) Why is my toString method not printing out the last node? It will not print...
(JAVA) Why is my toString method not printing out the last node? It will not print out "A" which is for Alice. Everything else is working just fine except for this. package driver; import exception.StackException; import stack.*; public class StackDriver { public static void main(String[] args) throws Exception { StackInterface<Painting> painting = new LinkedStack <Painting>(); try { System.out.println("Peeking at top of player stack.\n" + painting.peek()); }catch (StackException e) { System.out.println(e); System.out.println("Let's double check if it's empty: " + painting.isEmpty()); }...
Write code in java Implement a method to build an AVL tree out of a sorted...
Write code in java Implement a method to build an AVL tree out of a sorted (ascending order) array of unique integers, with the fastest possible big O running time. You may implement private helper methods as necessary. If your code builds a tree that is other than an AVL tree, you will not get any credit. If your code builds an AVL tree, but is not the fastest big O implementation, you will get at most 12 points. You...
You are given a reference to the root node of a binary search tree, that implements...
You are given a reference to the root node of a binary search tree, that implements a dictionary data structure. Please print all the elements in depths 500 through 510, all in sorted order. A node in a binary search tree is at depth x, if it takes x hops to get from the root. So the root is at depth 0, the children of the root are at depth 1, and so on. The class TreeNode defines a single...
10.6 LAB: Implement a stack using an array Given main() complete the Stack class by writing...
10.6 LAB: Implement a stack using an array Given main() complete the Stack class by writing the methods push() and pop(). The stack uses an array of size 5 to store elements. The command Push followed by a positive number pushes the number onto the stack. The command Pop pops the top element from the stack. Entering -1 exits the program. Ex. If the input is Push 1 Push 2 Push 3 Push 4 Push 5 Pop -1 the output...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT