Question

Write a Java program named BSTree.java that will: 1) Generate 20 random integer numbers ranging from...

Write a Java program named BSTree.java that will:

1) Generate 20 random integer numbers ranging from 1-99.

2) Build a Binary Search Tree using this set of numbers. Write the add method.

3) After building the tree, display the data into three formats: prefix order, infix order, and postfix order.

4) Write a method to delete an element from the Binary Search Tree. First search the item in your TREE and then delete it.

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

Code:

import java.util.*;

//Creating Node with Basic Functionalities
class BSTNode
{
     BSTNode left, right;
     int data;
     //An empty node
     public BSTNode()
     {
         left = null;
         right = null;
         data = 0;
     }
    //Creating a node with value n
     public BSTNode(int n)
     {
         left = null;
         right = null;
         data = n;
     }
     //Setting left node
     public void setLeft(BSTNode n)
     {
         left = n;
     }
    //Setting right node
     public void setRight(BSTNode n)
     {
         right = n;
     }
     //Function returns left node
     public BSTNode getLeft()
     {
         return left;
     }
     //Function returns right node
     public BSTNode getRight()
     {
         return right;
     }
     //Setting data to node
     public void setData(int d)
     {
         data = d;
     }
     //Getting data of node
     public int getData()
     {
         return data;
     }   
}

class BST
{
     BSTNode root;

     //Initially tree is null
     public BST()
     {
         root = null;
     }
     //Checking tree is empty or not
     public boolean isEmpty()
     {
         if(root == null)
           return true;
       else
           return false;
     }
   //Public method to get call from Main method of other class
   //Private method to get call from within the class
     public void add(int data)
     {
         root = add(root, data);
     }
    //Method to insert data
     private BSTNode add(BSTNode node, int data)
     {
       //If tree is empty then newNode will become root
         if (node == null)
             node = new BSTNode(data);
         //If tree is non empty
       else
         {
           //new node data is less than parent data then make it as left child
           //Otherwise make it as right child
             if (data < node.getData())
                 node.left = add(node.left, data);
             else
                 node.right = add(node.right, data);
         }
         return node;
     }
   public void prefixOrder()
   {
       prefixOrder(root);
   }
   //Preorder is root->left->right
   private void prefixOrder(BSTNode r)
     {
         if (r != null)
         {
             System.out.print(r.getData() +" ");
             prefixOrder(r.getLeft());           
             prefixOrder(r.getRight());
         }
     }
   public void infixOrder()
   {
       infixOrder(root);
   }
   //Inorder is left->root->right
   private void infixOrder(BSTNode r)
     {
         if (r != null)
         {
             infixOrder(r.getLeft());
           System.out.print(r.getData() +" ");
             infixOrder(r.getRight());
         }
     }
   public void postfixOrder()
   {
       postfixOrder(root);
   }
   //Postorder is left->right->root
   private void postfixOrder(BSTNode r)
     {
         if (r != null)
         {
             postfixOrder(r.getLeft());           
             postfixOrder(r.getRight());
           System.out.print(r.getData() +" ");
         }
     }
  
     public boolean search(int val)
     {
         return search(root, val);
     }
     //Method to search element
     private boolean search(BSTNode r, int val)
     {
         boolean found = false;
         while ((r != null) && !found)
         {
             int rval = r.getData();
           //If searching value is less that current node data then go left
             if (val < rval)
                 r = r.getLeft();
           //If searching value is less that current node data then go right
             else if (val > rval)
                 r = r.getRight();
           //If value is equal to current node data
             else
             {
                 found = true;
                 break;
             }
             found = search(r, val);
         }
         return found;
     }
  
   public void delete(int k)
     {
         if (isEmpty())
             System.out.println("Tree Empty");
         else if (search(k) == false)
             System.out.println("Sorry "+ k +" is not present");
         else
         {
             root = delete(root, k);
             System.out.println(k+ " deleted from the tree");
           System.out.println("\nAfter Deletion");
           System.out.println("\nPrefix order: ");prefixOrder();
           System.out.println("\nInfix order: ");infixOrder();
           System.out.println("\nPostfix order: ");postfixOrder();
         }
     }
     private BSTNode delete(BSTNode root, int k)
     {
         BSTNode p, p2, n;
       //If desired value found
         if (root.getData() == k)
         {
             BSTNode lt, rt;
             lt = root.getLeft();
             rt = root.getRight();
           //If single node present in tree
             if (lt == null && rt == null)
                 return null;
           //If node doesn't contain left node
             else if (lt == null)
             {
                 p = rt;
                 return p;
             }
           //If node doesn't contain right node
             else if (rt == null)
             {
                 p = lt;
                 return p;
             }
           //If node contains both the children
             else
             {
                 p2 = rt;
                 p = rt;
                 while (p.getLeft() != null)
                     p = p.getLeft();
                 p.setLeft(lt);
                 return p2;
             }
         }
       //If desired value is less than current node value then go left
         if (k < root.getData())
         {
             n = delete(root.getLeft(), k);
             root.setLeft(n);
         }
       //If desired value is greater than current node value then go right
         else
         {
             n = delete(root.getRight(), k);
             root.setRight(n);           
         }
         return root;
     }
}
public class BSTree
{
    public static void main(String args[])
    {
       //Creating object to Random() class
        Random r=new Random();
       //Creating object to BST class
       BST bst = new BST();
       //Generating 20 random numbers
        for(int i=0;i<20;)
       {
           int value=r.nextInt(100);
           if(value!=0)
           {
               bst.add(value);
               i++;
           }
       }
       System.out.println("\nPrefix order: ");bst.prefixOrder();
       System.out.println("\nInfix order: ");bst.infixOrder();
       System.out.println("\nPostfix order: ");bst.postfixOrder();
       Scanner sc=new Scanner(System.in);
       System.out.print("\nEnter deleting node value: ");
       int deleteValue=sc.nextInt();
       bst.delete(deleteValue);
    }
}

Output Screenshot:

Add a comment
Know the answer?
Add Answer to:
Write a Java program named BSTree.java that will: 1) Generate 20 random integer numbers ranging from...
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
  • Note: Once completed, run BXTDriver.class, then record the output to result.txt under your assignment folder. Without...

    Note: Once completed, run BXTDriver.class, then record the output to result.txt under your assignment folder. Without result.txt, you will receive zero(0) for this assignment. For this assignment, we will build a binary expression tree, display it, and evaluate it. This time, we will encapsulate the behavior in a BXT class. The driver class, tree node, as well as the BXT class are provided. Please implement appropriate methods in BXT class to build, display and evaluate a tree. Let's also allow...

  • Write a Java program that creates and manipulates a directory of names, telephone numbers. The following...

    Write a Java program that creates and manipulates a directory of names, telephone numbers. The following information will be stored for each person in the directory: - Name (Last, First) - Home telephone number You should keep the entire collection ordered by key value (the combination of last and first names). Your program should be able to perform the following basic functions: - Search and display the contents of a particular entry - Display the entire directory - Delete an...

  • Write a Java program that will create a random list (array) randomize a  search item to be...

    Write a Java program that will create a random list (array) randomize a  search item to be found in the list sequentially search the array for that item. You must code the search and not use a search function. Display each comparison in the array; the element contents and the index. display whether the item was found or not. Now take that code and alter it to have two lists. Both lists randomize between 1 and 50. While traversing one list,...

  • Assignment 4 1)For all the questions in Assignment 4, you need to draw a diagram to...

    Assignment 4 1)For all the questions in Assignment 4, you need to draw a diagram to describe the steps and provide short description as needed. Construct a Binary Search Tree by inserting the following node one by one. [4 points] 7,12,6,9,11,23,24,27,15 2)Provide an example for each following cases to search a given key in a Binary Search Tree. [4 points] Time efficiency=Ο(1)3S8CEMtd9AAAAAElFTkSuQmCC Time efficiency=ΟlogncdA3f5imtB2VefcxtquYZA8cQHOJLX+AydvU9UjZ Time efficiency=Ο(n)ZRO+N+OcdxOBP4CbNI+pPm7zwkAAAAASUVORK5CY 3)For the BST you created in question 1, delete the node 9, then 7,...

  • Assignment 4 1)For all the questions in Assignment 4, you need to draw a diagram to describe the ...

    Assignment 4 1)For all the questions in Assignment 4, you need to draw a diagram to describe the steps and provide short description as needed. Construct a Binary Search Tree by inserting the following node one by one. [4 points] 7,12,6,9,11,23,24,27,15 2)Provide an example for each following cases to search a given key in a Binary Search Tree. [4 points] Time efficiency=Ο(1)3S8CEMtd9AAAAAElFTkSuQmCC Time efficiency=ΟlogncdA3f5imtB2VefcxtquYZA8cQHOJLX+AydvU9UjZ Time efficiency=Ο(n)ZRO+N+OcdxOBP4CbNI+pPm7zwkAAAAASUVORK5CY 3)For the BST you created in question 1, delete the node 9, then 7,...

  • 1. Write a C code that do the following: Generate array of random integer numbers of...

    1. Write a C code that do the following: Generate array of random integer numbers of size 25 Fill the array with random integers ranging from [1-100] Find the maximum number of the array and its location Find the minimum number of the array and its location Search for a number in the array Print the array Flip the array Sort this array Quit the program when the user choose to exit

  • Write a Java program with a single-dimension array that holds 11 integer numbers and sort the...

    Write a Java program with a single-dimension array that holds 11 integer numbers and sort the array using a bubble sort. Next, identify the median value of the 11 integers. Here are the steps your program must accomplish. algorithm (either flowchart or pseudocode) that you will use to write the program Step 1. Create an Place the algorithm in a Word document. 6. Ste the Step 2. Code the program in Eclipse and ensure the following steps are accomplished. 1....

  • JAVA CODE Write a JAVA program to do the following. Input an integer x. (Should work...

    JAVA CODE Write a JAVA program to do the following. Input an integer x. (Should work with “big” numbers.) Create a completely-skewed BST S containing 1, 2, . . . , x. Create a BST R containing x integers without repetitions gen- erated at random. (To minimize the risk of repetitions, you can multiply the value returned by random() by a big number.) Given that the numbers are generated uniformly at random, the tree will likely be balanced. Measure the...

  • C++ C++ Write a program to input eight integer numbers into an array named grade. As...

    C++ C++ Write a program to input eight integer numbers into an array named grade. As each number is input, add the number into a total. After all numbers are input, display the numbers and their average. (You can use cin to take number or use rand() to assign random numbers to the array.)

  • Write Java program to compare time consumed by linear search and binary search to search for...

    Write Java program to compare time consumed by linear search and binary search to search for non-exit element in arrays of length 1000, 100000,500000,1000000. Hints: - Use Random class, method nextInt(a.length) to generate random numbers. - Select an element that is greater than a.length. - Use Arrays.sort(a) to sort the array before using binarySearch.

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