Question

In: Computer Science

Implement two methods, find() and replace() relating to Binary Search Trees. Both of these methods must...

Implement two methods, find() and replace() relating to Binary Search Trees. Both of these methods must be recursive functions. The signatures for the functions must be:

 /* This method takes a tree node and a key as an argument and returns the tree node if the key is found and returns null if the key is not found. */ 
BST find(BST T, char key)
/* This method takes a tree node and a key as an argument and inserts the tree node if the key is already in the tree it does not insert the node. */
BST insert(BST T, char key)

You will also implement the preOrder(), inOrder(), and postOrder() tree traversal methods. These methods must also be recursive functions. The input for this program will be from the keyboard and accept single-character keys, labeled 'A' - 'Z'.

Rules:

1) You cannot delete any code in the BST class, adding code is okay.

2) All 5 methods MUST be RECURSIVE. No credit is given if a method is not recursive, even if it works correctly.

3) Do not assume any maximum length for any input string.

4) Do not need to test for an empty string or null case.

5) You are not allowed to add any arrays or ArrayLists or any Java built-in (ADTs), such as Lists, Sets, Maps, Stacks, Queues, Deques, Trees, Graphs, Heaps, etc. or add any class that inherits any of those ADTs.

6) The use of Java Generics is also not allowed.

Starter code which must be used:

import java.util.Scanner; // Import the Scanner class

public class BST {
  
public char key;
public BST left;
public BST right;

public BST(char c) {
key = c;
left = null;
right = null;
}
  
public static BST find(BST T, char key) {
// put your solution here
}

public static BST insert(BST T, char key) {
// put your solution here
}
  
public static void preOrder(BST T) {
// put your solution here
}
  
public static void inOrder(BST T) {
// put your solution here
}
  
public static void postOrder(BST T) {
// put your solution here
}
  
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
BST t = null;
String stream = input.nextLine();
for (int i = 0; i < stream.length(); i++)
t = insert(t, stream.charAt(i));
System.out.print("Preorder: ");
preOrder(t);
System.out.println();
System.out.print("Inorder: ");
inOrder(t);
System.out.println();
System.out.print("Postorder: ");
postOrder(t);
System.out.println();
System.out.println("Enter a character to search for: ");
char c = input.nextLine().charAt(0);
if (find(t, c) == null)
System.out.println("The character " + "'" + c + "' was not found.");
else
System.out.println("The character " + "'" + c + "' was found.");
}

Solutions

Expert Solution

Java code:

import java.util.Scanner; // Import the Scanner class

public class BST {

    public char key;
    public BST left;
    public BST right;

    public BST(char c) {
        key = c;
        left = null;
        right = null;
    }

    /**
     *
     * @param T BST
     * @param key key to find
     * @return The BST node if found. Otherwise null
     */
    public static BST find(BST T, char key) {
        if (T==null || T.key==key)
            return T;

        // key is greater than T's key
        if (T.key > key)
            return find(T.left, key);

        // key is less than T's key
        return find(T.right, key);
    }

    /**
     *
     * @param T BST to insert the key into
     * @param key The key to be insertes
     * @return BST after insertion
     */
    public static BST insert(BST T, char key) {
        // Create and insert a new node
        if (T == null) {
            T = new BST(key);
            return T;
        }

        // if key is already present don't insert and return unchanged pointer
        if(T.key == key)
            return T;

        // Otherwise, recur down the tree
        if (key < T.key)
            T.left = insert(T.left, key);
        else if (key > T.key)
            T.right = insert(T.right, key);

        // return the unchanged pointer
        return T;
    }

    /**
     * Preorder traversal of the BST
     *
     * @param T BST
     */
    public static void preOrder(BST T) {
        if(T==null)
            return;
        System.out.print(T.key+" ");
        preOrder(T.left);
        preOrder(T.right);
    }

    /**
     * Inorder traversal of the BST
     *
     * @param T BST
     */
    public static void inOrder(BST T) {
        if(T==null)
            return;
        inOrder(T.left);
        System.out.print(T.key+" ");
        inOrder(T.right);
    }

    /**
     * Postorder traversal of the BST
     *
     * @param T BST
     */
    public static void postOrder(BST T) {
        if(T==null)
            return;
        postOrder(T.left);
        postOrder(T.right);
        System.out.print(T.key+" ");
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        BST t = null;
        String stream = input.nextLine();
        for (int i = 0; i < stream.length(); i++)
            t = insert(t, stream.charAt(i));
        System.out.print("Preorder: ");
        preOrder(t);
        System.out.println();
        System.out.print("Inorder: ");
        inOrder(t);
        System.out.println();
        System.out.print("Postorder: ");
        postOrder(t);
        System.out.println();
        System.out.println("Enter a character to search for: ");
        char c = input.nextLine().charAt(0);
        if (find(t, c) == null)
            System.out.println("The character " + "'" + c + "' was not found.");
        else
            System.out.println("The character " + "'" + c + "' was found.");
    }
}

Output:


Related Solutions

In Java For this assignment you will implement two methods, find() and replace() relating to Binary...
In Java For this assignment you will implement two methods, find() and replace() relating to Binary Search Trees. These methods are both to be recursive functions. The signatures for those functions must be: /* This method takes a tree node and a key as an argument and returns the tree node if the key is found and returns null if the key is not found. */ BST find(BST T, char key) /* This method takes a tree node and a...
Implement a function to find a node in a binary search tree. Using the following class...
Implement a function to find a node in a binary search tree. Using the following class and function definition. If a node with a matching value is found, return a pointer to it. If no match is found, return nullptr. #include <iostream> class BTNode { public: int item; BTNode *left; BTNode *right; BTNode(int i, BTNode *l=nullptr, BTNode *r=nullptr):item(i),left(l),right(r){} }; BTNode *root = nullptr; BTNode *find(int item) { //implement code here return nullptr; } int main() {    root = new...
Lab 5: Binary Search Tree Implement operations for a Binary Search Tree class starting from the...
Lab 5: Binary Search Tree Implement operations for a Binary Search Tree class starting from the template provided under the PolyLearn assignment, using the class TreeNode that is also provided. You may (should) implement helper methods that make your code easier to write, read, and understand. You will also need to write test cases of your own as you develop the methods. You may use iterative and/or recursive functions in your implementation. The following starter files are available . •...
Derive a recurrence for the number of degenerate binary search trees that can be generated from...
Derive a recurrence for the number of degenerate binary search trees that can be generated from a given sequence of n distinct elements. Recall that degenerate binary search tree contains no branches and thus is structurally similar to a linked list. You must make an argument to justify each component of your recurrence. Remember that all recurrences have base cases so do not forget to include a base case.
Research the topic of binary search trees. Write a brief summary of your understanding of this....
Research the topic of binary search trees. Write a brief summary of your understanding of this. Design a simple program, using pseudocode, that performs a search of a binary search tree.. In your own words, explain how a binary search tree works using graph theory terminology. Construct a binary search tree for any alphabetically ordered list of five words. Represent it visually as a graph. Discuss any characteristics you note about the graph you created in part (d). In your...
Java String search Design and implement a recursive version of a binary search.  Instead of using a...
Java String search Design and implement a recursive version of a binary search.  Instead of using a loop to repeatedly check for the target value, use calls to a recursive method to check one value at a time.  If the value is not the target, refine the search space and call the method again.  The name to search for is entered by the user, as is the indexes that define the range of viable candidates can be entered by the user (that are...
I am trying to implement a search function for a binary search tree. I am trying...
I am trying to implement a search function for a binary search tree. I am trying to get the output to print each element preceding the the target of the search. For example, in the code when I search for 19, the output should be "5-8-9-18-20-19" Please only modify the search function and also please walk me through what I did wrong. I am trying to figure this out. Here is my code: #include<iostream> using namespace std; class node {...
Implement a recursive binary search on an array of 8-byte integers in LEGV8
Implement a recursive binary search on an array of 8-byte integers in LEGV8
PYTHON CODING Using the structural node and methods discussed in Binary Search Tree below # Binary...
PYTHON CODING Using the structural node and methods discussed in Binary Search Tree below # Binary Tree Node structure class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None class BSTree(): def __init__(self, rootdata): self.root = Node(rootdata)    def insert(self, data, cur_node): if data < cur_node.data: if cur_node.left == None: cur_node.left = Node(data) else: self.insert(data, cur_node.left)    elif data > cur_node.data: if cur_node.right == None: cur_node.right = Node(data) else:...
In MobaXterm, with the use of the binary search tree. Implement four operations of insert, in-order...
In MobaXterm, with the use of the binary search tree. Implement four operations of insert, in-order traversal, preorder traversal, and find. Please separate the code in the four parts and explain in detail what is happening. Also, if you can please basic C language. If not, then I understand. Thank you for your time. The test cases are 'm', 'd', 'g', 'r', 'p', 'b', and 'x'. Output: Enter choice (lower case is also acceptable) --- (I)nsert, (F)ind, (Q)uit: i Enter...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT