Question

In: Computer Science

Write methods contains and remove for the BinarySearchTree class. Use methods find and delete to do...

Write methods contains and remove for the BinarySearchTree class. Use methods find and delete to do the work

Solutions

Expert Solution

Code :
class Node
{
    public int data;
    public Node left;
    public Node right;
    public Node parent;

    public Node(int data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
        this.parent = null;
    }
}

class BinarySearchTree
{
    public Node root;

    public BinarySearchTree()
    {
        this.root = null;
    }

    public Node minimum(Node x)
    {
        while(x.left != null)
            x = x.left;
        return x;
    }

    public void insert(Node n)
    {
        Node y = null;
        Node temp = this.root;
        while(temp != null)
        {
            y = temp;
            if(n.data < temp.data)
                temp = temp.left;
            else
                temp = temp.right;
        }
        n.parent = y;

        if(y == null) //newly added node is root
            this.root = n;
        else if(n.data < y.data)
            y.left = n;
        else
            y.right = n;
    }

    public void transplant(Node u, Node v)
    {
        if(u.parent == null) //u is root
            this.root = v;
        else if(u == u.parent.left) //u is left child
            u.parent.left = v;
        else //u is right child
            u.parent.right = v;

        if(v != null)
            v.parent = u.parent;
    }

    public void delete(Node z)
    {
        if(z.left == null)
        {
            transplant(z, z.right);
        }
        else if(z.right == null)
        {
            transplant(z, z.left);
        }
        else
            {
                Node y = minimum(z.right); //minimum element in right subtree
                if(y.parent != z) {
                    transplant(y, y.right);
                    y.right = z.right;
                    y.right.parent = y;
            }
            transplant(z, y);
            y.left = z.left;
            y.left.parent = y;
        }
    }

    public void inorder(Node n)
    {
        if(n != null)
        {
            inorder(n.left);
            System.out.println(n.data);
            inorder(n.right);
        }
    }
    public static boolean searchRecursively(Node root, int value) {


        if (root == null)
            return false;


        if ((int) root.data == value)
            return true;

        if (value < (int) root.data)
            return searchRecursively(root.left, value);

        else if (value > (int) root.data)
            return searchRecursively(root.right, value);


        return false;
    }
    public static void main(String[] args)
    {
        BinarySearchTree t = new BinarySearchTree();

        Node a, b, c, d, e, f, g, h, i, j, k, l, m;
        a = new Node(1);
        b = new Node(2);
        c = new Node(3);
        d = new Node(10);
        e = new Node(9);
        f = new Node(4);
        g = new Node(59);
        h = new Node(6);
        i = new Node(790);
        j = new Node(800);

        System.out.println("After insert");
        t.insert(a);
        t.insert(b);
        t.insert(c);
        t.insert(d);
        t.insert(e);
        t.insert(f);
        t.insert(g);
        t.insert(h);
        t.insert(i);
        t.insert(j);

        t.inorder(t.root);
        System.out.println("--------------------------------------------------------------");
        System.out.println("After Delete");

        t.delete(a);
        t.delete(e);

        t.inorder(t.root);
        System.out.println("--------------------------------------------------------------");
        System.out.println("Search element ");


        System.out.println("Search Value 503 is in tree? " + searchRecursively(t.root, 503));
        System.out.println("Search Value 4 in tree? " + searchRecursively(t.root, 4));
        System.out.println("Search Value 6 in tree? " + searchRecursively(t.root, 6));
        System.out.println("Search Value 401 in tree? " + searchRecursively(t.root, 401));
    }
}

output:

After insert
1
2
3
4
6
9
10
59
790
800
-------------------------------------------------------------------------
After Delete
2
3
4
6
10
59
790
800
-------------------------------------------------------------------------
Search element
Search Value 503 is in tree? false
Search Value 4 in tree? true
Search Value 6 in tree? true
Search Value 401 in tree? false

output(SS):

Explain:

Binary Search Tree is a special kind of binary tree in which the values of all the nodes of the left subtree of any node of the tree are smaller than the value of the node. Also, the values of all the nodes of the right subtree of any node are greater than the value of the node.


Related Solutions

Complete the three empty methods (remove(), find(), and contains()) in the ShoppingListArrayList.java file. These methods are...
Complete the three empty methods (remove(), find(), and contains()) in the ShoppingListArrayList.java file. These methods are already implemented in the ShoppingListArray class. Complete the ShoppingListArrayListTest.java (For many tests, we now just throw a false statement which will cause the test cases to fail. You need to complete them.) ShoppingListArrayList package Shopping; import DataStructures.*; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; /** * @version Spring 2019 * @author Paul Franklin, Kyle Kiefer */ public class ShoppingListArrayList implements ShoppingListADT { private ArrayList<Grocery> shoppingList;...
Use Selections, DO NOT USE ARRAYS AND METHODS. (Find future dates) Write a program that prompts...
Use Selections, DO NOT USE ARRAYS AND METHODS. (Find future dates) Write a program that prompts the user to enter an integer for today’s day of the week (Sunday is 0, Monday is 1, ..., and Saturday is 6). Also prompt the user to enter the number of days after today for a future day and display the future day of the week. ** Can not use java.time.DayOfWeek; SAMPLE RUN #1: java FindFutureDates Enter today's day: 4↵ Enter the number...
A Java question. Write the class Staff. It contains methods that manipulate an ArrayList of Strings...
A Java question. Write the class Staff. It contains methods that manipulate an ArrayList of Strings representing the names of staff members. The constructor takes an ArrayList of String names as a parameter. In addition to the constructor, you need to implement the following methods The methods 1. public boolean equals(Staff other) - Determines if the other Staff contains all the same elements in the same order as this Staff 2. public boolean sameContents(Staff other) - Determines if the other...
Write a remove(E val) method for DoublyLinkedList class This method remove the first occurrence of the...
Write a remove(E val) method for DoublyLinkedList class This method remove the first occurrence of the node that contains the val. .
Write a remove(E val) method for CircularlyLinkedList class This method remove the first occurrence of the...
Write a remove(E val) method for CircularlyLinkedList class This method remove the first occurrence of the node that contains the val.
Write a Calculate class which contains methods that accepts two integers as arguments and return the...
Write a Calculate class which contains methods that accepts two integers as arguments and return the results of Addition, Subtraction, Division and Multiplication. Call these methods though main()and print the results.
Extend the custom unorderedLinkedList class by adding the following operation: Find and delete the node with...
Extend the custom unorderedLinkedList class by adding the following operation: Find and delete the node with the smallest info in the list. Delete only the first occurrence and traverse the list only once. The function's prototype is deleteSmallest() use this code #include <ctime> #include <iostream> #include <random> #include "unorderedLinkedList.h" using namespace std; int main() { default_random_engine e(1918); uniform_int_distribution<int> u(10, 99); int size = 12; unorderedLinkedList ul; while (ul.getnelts() < size) { int elt = u(e); ul.append(elt); ul.show(); cout << endl;...
Write a simple java class that contains the following three methods: 1. isosceles -- accepts 3...
Write a simple java class that contains the following three methods: 1. isosceles -- accepts 3 integers which represent the sides of a triangle. Returns true if the triangle is isosceles and false otherwise. 2. perimeter - accepts 3 integers that represent the sides of a triangle and returns the perimeter of the triangle. 3. area -- accepts 3 integers, which represent the sides of a triangle and calculates and returns the area of the triangle. Hint: use Heron's formula....
Write the methods that insert and remove an element at the kth position in Java using...
Write the methods that insert and remove an element at the kth position in Java using recursion (NOT iteration) (Hint for the remove method: we have to recursive position -1 times, and each time we do the recursion, we have to create a method to move the head to the right) public void insertRecursive(int position, int data) { //enter code here } public int removeAtRecursive(int position) { //enter code here } Here is the given class for the Node: public...
Write the class RecursiveProbs, with the methods listed below. Write all the methods using recursion, not...
Write the class RecursiveProbs, with the methods listed below. Write all the methods using recursion, not loops. You may use JDK String methods like substring() and length(), but do not use the JDK methods to avoid coding the algorithms assigned. For example, don't use String.reverse(). public boolean recursiveContains(char c, String s) returns true if the String contains the char, otherwise returns false. Here is the code for this method, which you should use as an example to see how to...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT