Question

BST JAVA FILE import java.util.*; public class BST <E extends Comparable <E>> {    private TreeNode<E>...

BST JAVA FILE

import java.util.*;

public class BST <E extends Comparable <E>> {
   private TreeNode<E> overallRoot;

   public BST() {
       overallRoot = null;
   }

   // ************ ADD ************ //
   public void add(E addThis) {
       if (overallRoot == null) {
           overallRoot = new TreeNode<>(addThis);
       } else {
           add(overallRoot, addThis);
       }
   }

   private TreeNode<E> add(TreeNode<E> node, E addThis) {
       if (node == null) {
           return new TreeNode<>(addThis);
       } else if (node.data.compareTo(addThis) > 0) {
           node.left = add(node.left, addThis);
       } else {
           node.right = add(node.right, addThis);
       }

       return node;
   }

   // ************ SEARCH ************ //
   public TreeNode<E> search(E find) {
       return search(overallRoot, find);
   }

   private TreeNode<E> search(TreeNode<E> node, E find) {
       if (node == null || node.data.equals(find)) {
           return node;
       } else if (node.data.compareTo(find) > 0) {
           return search(node.left, find);
       } else {
           return search(node.right, find);
       }
   }

   // ************ REMOVE ************ //
   public void remove(E deleteThis) {
       overallRoot = remove(overallRoot, deleteThis);
   }

   private TreeNode<E> remove(TreeNode<E> node, E deleteThis) {
       if (node == null) {
return null;
} else if (node.data.compareTo(deleteThis) > 0) {
               node.left = remove(node.left, deleteThis);
   } else if (node.data.compareTo(deleteThis) < 0) {
               node.right = remove(node.right, deleteThis);
   }
       else { // if (node.data.equals(deleteThis)) {
if (node.left == null) {
               return node.right;
           } else if (node.right == null) {
               return node.left;
} else {
            node.data = findMax(node.left);
            node.left = remove(node.left, node.data);
}
       }
return node;
   }

// Returns the largest value from this node + it's subtree
   private E findMax(TreeNode<E> node) {
       return null;
   }

   // ************ PRINT ************ //
   public void print() {
System.out.print("In order = ");
       printInorder(overallRoot);
System.out.println();
   }

   private void printInorder(TreeNode<E> root) {
       if (root != null) {
           printInorder(root.left);
           System.out.print(root.data + " ");
           printInorder(root.right);
       }
   }

   // ************ NORMAL BINARY TREE OPERATIONS ************ //
   public int countLeaves() {
       return countLeaves(overallRoot);
   }

   private int countLeaves(TreeNode<E> node) {
       if (node == null) {
           return 0;
} else if (node.left == null && node.right == null) {
           return 1;
       } else {
           return countLeaves(node.left) + countLeaves(node.right);
}
   }

// Returns the number of nodes total in the tree
public int countNodes() {
return 0;
}

// Returns the number of children for this value
   public int countChildren(E data) {
       return 0;
   }

// ************ BST OPERATIONS ************ //
public E max() {
return findMax(overallRoot);
}

public boolean isBST() {
return isBST(overallRoot);
}

private boolean isBST(TreeNode<E> node) {
if (node == null) {
return true;
} else {
boolean leftCheck = node.left == null ? true : node.data.compareTo(node.left.data) > 0;
boolean rightCheck = node.right == null ? true : node.data.compareTo(node.right.data) < 0;
return leftCheck && rightCheck && isBST(node.left) && isBST(node.right);
}
}

// Returns if the tree is balanced or not
public boolean isBalanced() {
return false;
}

// ========== MAIN ==========
public static void main(String[] args) {
int[] numbers = {20, 30, 5, 6};
int[] numbers2 = {13, 10, 5, -8, 2, 17, -4, 6};
int[] numbers3 = {5, 4, 7, 3, 9, 6};
  
BST<Integer> bst = new BST<>();
for(int n : numbers)
bst.add(n);
  
System.out.println("==== Tree Info ==== ");
bst.print();
System.out.println("Count of nodes = " + bst.countNodes());
System.out.println("The largest value in the tree is " + bst.max() + ".");
System.out.println("Node 5 has " + bst.countChildren(5) + " children.");
System.out.println("Node 6 has " + bst.countChildren(6) + " children.");
System.out.println("isBalanced? " + bst.isBalanced());
System.out.println("isBST? " + bst.isBST());
}

} //end of BST

--------------------------------------------------------------------------------------------------------------

BST TESTER

public class BSTTester {
public static void main(String[] args) {
int[] numbers = {20, 30, 5, 6};
int[] numbers2 = {13, 10, 5, -8, 2, 17, -4, 6};
int[] numbers3 = {5, 4, 7, 3, 9, 6};
  
BST<Integer> bst = new BST<>();
for(int n : numbers)
bst.add(n);
  
System.out.println("==== Tree Info ==== ");
bst.print();
System.out.println("Count of nodes = " + bst.countNodes());
System.out.println("The largest value in the tree is " + bst.max() + ".");
System.out.println("Node 5 has " + bst.countChildren(5) + " children.");
System.out.println("Node 6 has " + bst.countChildren(6) + " children.");
System.out.println("isBalanced? " + bst.isBalanced());
System.out.println("isBST? " + bst.isBST());
}
}

---------------------------------------------------------------------------------------------------------

TREE NODE

import java.util.*;

public class TreeNode<E extends Comparable<E>> {
public E data;
public TreeNode<E> left;
public TreeNode<E> right;
  
// constructs a leaf node with given data
public TreeNode(E data) {
this(data, null, null);
}
  
// constructs a branch node with given data, left subtree, right subtree
public TreeNode(E data, TreeNode<E> left, TreeNode<E> right) {
this.data = data;
this.left = left;
this.right = right;
}
  
public int compareTo(TreeNode<E> other) {
return this.data.compareTo(other.data);
}
}

--------------------------------------------------------------------

Part 1: Check out BST

  • Step through how add(addThis) works
  • Step through remove(deleteThis)

Part 2: Add functionality to BST

  • Write findMax(node)
  • Check out countLeaves()
  • Write countNodes()
  • Write countChildren()

Offline

Part 3: More BST

  • Add comments to add() and search() to show that you understand how those methods work
  • Write isBalanced()
  • Add a numbers4 to your main that generates a balanced BST with at least 4 levels.

What to Submit

  • Your completed BST.java
  • A screenshot of your built numbers4 BST from debug mode
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Summary :

This solution is provided with following :

1)Notes on implementation .

2) Code

3) output

Notes on Implementation :

Provided details notes and comments inline in the code in file BST.java after implementing the required functionality.

added getHeight() and isBalanced() functions for the isBalanced() function implementation .

Restructured the BSTTester.java code to test numberous arrays by introducing static method TestTree() which accepts a integer array .

############### Code ##############

BST.java

import java.util.*;

import java.math.*;

public class BST <E extends Comparable <E>> {

   private TreeNode<E> overallRoot;

   public BST() {

       overallRoot = null;

   }

   // ************ ADD ************ //

   /**

    * This method takes help of recursive function add(TreeNode, E) ( which is also a overloaded function )

    * to add an element with value addThis .

    * @param addThis - The value to be added to the BST

    */

   public void add(E addThis) {

       // If the Root node is null insert the node and make it root node

       if (overallRoot == null) {

           overallRoot = new TreeNode<>(addThis);

       } else {

           // Take help of recursive add function to add the value - addThis at the right place

           add(overallRoot, addThis);

       }

   }

   /**

    * This recursive function add the value - addThis under the give node by checking whether its value

    * is greater or less than current given node - node and tries to add it to under its left subtree

    * or right subtree .

    * This recursive function ends when it reaches  empty left or right subtree and inserts the node and returns its

    * value otherwise it just returns the current node value .

    * @param node -  given node under which value needs to be added

    * @param addThis - Given value that should be added to the BST

    * @return -  Returns the TreeNode where its added

    */

   private TreeNode<E> add(TreeNode<E> node, E addThis) {

       // If node is null the recursive function will

       // create a new node add the value and return the value of Node

       if (node == null) {

           return new TreeNode<>(addThis);

       } else if (node.data.compareTo(addThis) > 0) {

           // In case addThis value is less than current node

           // try to add it under left subtree

           node.left = add(node.left, addThis);

       } else {

           // In case addThis value is greater than currentNode

           //recursively try to add it under right sub tree

           node.right = add(node.right, addThis);

       }

       return node;

   }

   // ************ SEARCH ************ //

   /**

    * This search method searches the given value 'find' in the given tree

    * if success returns the node value else null

    * @param find - Value to be found in the tree

    * @return - TreeNode value

    */

   public TreeNode<E> search(E find) {

       // REcursively find for value - find in Tree with head - overallRoot

       return search(overallRoot, find);

   }

   /**

    * This function recursively searces for value - find under the tree pointed by

    * given node . It check if the root node value matches the given values , else

    * it checks to see whether to recursively search for left or right based on

    * compareTo() value of given node and find value and accordingly searches in left subtree

    * or right subtree .

    * @param node

    * @param find

    * @return

    */

   private TreeNode<E> search(TreeNode<E> node, E find) {

       // If node is not null and node value is equal to find return the node itself

       if (node == null || node.data.equals(find)) {

           return node;

       } else if (node.data.compareTo(find) > 0) {

           // Search left subtree if the value of find <  node data

           return search(node.left, find);

       } else {

           // Search right subtree if the value of find >  node data

           return search(node.right, find);

       }

   }

   // ************ REMOVE ************ //

   public void remove(E deleteThis) {

       overallRoot = remove(overallRoot, deleteThis);

   }

   private TreeNode<E> remove(TreeNode<E> node, E deleteThis) {

       if (node == null) {

            return null;

        } else if (node.data.compareTo(deleteThis) > 0) {

                    node.left = remove(node.left, deleteThis);

        } else if (node.data.compareTo(deleteThis) < 0) {

                    node.right = remove(node.right, deleteThis);

        }

            else { // if (node.data.equals(deleteThis)) {

        if (node.left == null) {

                    return node.right;

                } else if (node.right == null) {

                    return node.left;

        } else {

                    node.data = findMax(node.left);

                    node.left = remove(node.left, node.data);

        }

            }

        return node;

   }

// Returns the largest value from this node + it's subtree

   private E findMax(TreeNode<E> node)

   {

       TreeNode<E> tmpNode = node ;

       while ( tmpNode.right != null )

       {

           tmpNode = tmpNode.right;

       }

       if ( tmpNode != null )

           return tmpNode.data ;

       else

           return null;

   }

   // ************ PRINT ************ //

   public void print() {

        System.out.print("In order = ");

            printInorder(overallRoot);

        System.out.println();

   }

   private void printInorder(TreeNode<E> root) {

       if (root != null) {

           printInorder(root.left);

           System.out.print(root.data + " ");

           printInorder(root.right);

       }

   }

   // ************ NORMAL BINARY TREE OPERATIONS ************ //

   public int countLeaves() {

       return countLeaves(overallRoot);

   }

   private int countLeaves(TreeNode<E> node) {

       if (node == null) {

           return 0;

        } else if (node.left == null && node.right == null) {

           return 1;

        } else {

           return countLeaves(node.left) + countLeaves(node.right);

        }

   }

// Returns the number of nodes total in the tree

    public int countNodes() {

        return countNodes(overallRoot);

    }

    public int countNodes( TreeNode<E> thisNode )

    {

        if ( thisNode == null )

            return 0 ;

        

        int numNodes_LeftSide = 0 ;

        int numNodes_RightSide = 0 ;

        if ( thisNode.left != null )

            numNodes_LeftSide = countNodes(thisNode.left);

        

        if ( thisNode.right != null )

            numNodes_RightSide = countNodes(thisNode.right);

        

        //System.out.format(" %d %d \n", numNodes_LeftSide,numNodes_RightSide);

        return 1 + numNodes_LeftSide + numNodes_RightSide;

    }

// Returns the number of children for this value

   public int countChildren(E data) {

       TreeNode<E> tmpNode = search( data );

       return countNodes(tmpNode) - 1;

   }

// ************ BST OPERATIONS ************ //

public E max() {

return findMax(overallRoot);

}

public boolean isBST() {

return isBST(overallRoot);

}

private boolean isBST(TreeNode<E> node) {

    if (node == null) {

        return true;

    } else {

        boolean leftCheck = node.left == null ? true : node.data.compareTo(node.left.data) > 0;

        boolean rightCheck = node.right == null ? true : node.data.compareTo(node.right.data) < 0;

        return leftCheck && rightCheck && isBST(node.left) && isBST(node.right);

    }

}

// Returns if the tree is balanced or not

    public boolean isBalanced() {

        return isBalanced(overallRoot);

        

    }

    /**

     * This method recursively finds whether left subtree is balanced

     * and right subtree is balanced in addition checks if left subtree Height

     * and right Subtree height diff is not > 1 to return True

     *

     * @param node

     * @return

     */

    private boolean isBalanced(TreeNode<E> node )

    {

        if ( node == null )

            return true ;

        int leftHeight = getHeight(node.left);

        int rightHeight = getHeight(node.right);

        

        if (( Math.abs( leftHeight - rightHeight ) <= 1 )

            & isBalanced(node.left) & isBalanced(node.right))

            return true ;

        return false;

    }

    /**

     * This method recursively finds the height of left subtree

     * and right subtree and returns by checking max of both the tree

     * as height of the tree of given node

     * @param node

     * @return

     */

    private int getHeight(TreeNode<E> node )

    {

        if ( node == null  )

            return 0 ;

        else

        {

            int leftHeight = getHeight(node.left) ;

            int rightHeight = getHeight(node.right);

            if ( leftHeight > rightHeight)

                return 1 + leftHeight ;

            else

                return 1 + rightHeight;

        }

    }

// ========== MAIN ==========

public static void main(String[] args) {

    int[] numbers = {20, 30, 5, 6 };

    int[] numbers2 = {13, 10, 5, -8, 2, 17, -4, 6};

    int[] numbers3 = {5, 4, 7, 3, 9, 6};

    

    BST<Integer> bst = new BST<>();

    for(int n : numbers)

        bst.add(n);

    

    System.out.println("==== Tree Info ==== ");

    bst.print();

    System.out.println("Count of nodes = " + bst.countNodes());

    System.out.println("The largest value in the tree is " + bst.max() + ".");

    System.out.println("Node 5 has " + bst.countChildren(5) + " children.");

    System.out.println("Node 6 has " + bst.countChildren(6) + " children.");

    System.out.println("isBalanced? " + bst.isBalanced());

    System.out.println("isBST? " + bst.isBST());

}

} //end of BST

###

BSTTester.java

###

//BST TESTER

import java.util.Random;

public class BSTTester {

public static void TestTree( int[] numbers )

{

    Random rand = new Random();

    BST<Integer> bst = new BST<>();

    for(int n : numbers)

        bst.add(n);

    

    

Know the answer?
Add Answer to:
BST JAVA FILE import java.util.*; public class BST <E extends Comparable <E>> {    private TreeNode<E>...
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
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
ADVERTISEMENT