Question

In: Computer Science

In C++ I just need a MAIN that uses the steps and uses the functions and...

In C++ I just need a MAIN that uses the steps and uses the functions and class given below.

Implement the BinarySearchTree ADT in a file BinarySearchTree.h exactly as shown below.

// BinarySearchTree.h
// after Mark A. Weiss, Chapter 4, Dr. Kerstin Voigt

#ifndef BINARY_SEARCH_TREE_H
#define BINARY_SEARCH_TREE_H

#include 
#include 
using namespace std;      

template 
class BinarySearchTree
{
  public:
    BinarySearchTree( ) : root{ nullptr }
    {
    }

    ~BinarySearchTree( ) 
    { 
        makeEmpty();
    }

    const C & findMin( ) const
    {
      assert(!isEmpty());
      return findMin( root )->element;
    }

    const C & findMax( ) const
    {
      assert(!isEmpty());
      return findMax( root )->element;
    }

    bool contains( const C & x ) const
    {
        return contains( x, root );
    }

    bool isEmpty( ) const
    {
        return root == nullptr;
    }

    void printTree( ) const
    {
        if( isEmpty( ) )
            cout << "Empty tree" << endl;
        else
            printTree( root );
    }

    void makeEmpty( )
    {
        makeEmpty( root );
    }
    
    void insert( const C & x )
    {
        insert( x, root );
    }     

    void remove( const C & x )
    {
        remove( x, root );
    }

  private:
    
    struct BinaryNode
    {
        C element;
        BinaryNode* left;
        BinaryNode* right;

        BinaryNode( const C & theElement, BinaryNode* lt, BinaryNode* rt )
          : element{ theElement }, left{ lt }, right{ rt } { }
    };

    BinaryNode* root;
    
    // Internal method to insert into a subtree.
    // x is the item to insert.
    // t is the node that roots the subtree.
    // Set the new root of the subtree.    
    void insert( const C & x, BinaryNode* & t )
    {
        if( t == nullptr )
            t = new BinaryNode{ x, nullptr, nullptr };
        else if( x < t->element )
            insert( x, t->left );
        else if( t->element < x )
            insert( x, t->right );
        else
            ;  // Duplicate; do nothing
    }
    
    // Internal method to remove from a subtree.
    // x is the item to remove.
    // t is the node that roots the subtree.
    // Set the new root of the subtree.    
    void remove( const C & x, BinaryNode* & t )
    {
        if( t == nullptr )
            return;   // Item not found; do nothing
        if( x < t->element )
            remove( x, t->left );
        else if( t->element < x )
            remove( x, t->right );
        else if( t->left != nullptr && t->right != nullptr ) // Two children
        {
            t->element = findMin( t->right )->element;
            remove( t->element, t->right );
        }
        else
        {
            BinaryNode* oldNode = t;
            t = ( t->left != nullptr ) ? t->left : t->right;
            delete oldNode;
        }
    }

    // Internal method to find the smallest item in a subtree t.
    // Return node containing the smallest item.    
    BinaryNode* findMin( BinaryNode* t ) const
    {
        if( t == nullptr )
            return nullptr;
        if( t->left == nullptr )
            return t;
        return findMin( t->left );
    }
    
    // Internal method to find the largest item in a subtree t.
    // Return node containing the largest item.
    BinaryNode* findMax( BinaryNode* t ) const
    {
        if( t != nullptr )
            while( t->right != nullptr )
                t = t->right;
        return t;
    }

    // Internal method to test if an item is in a subtree.
    // x is item to search for.
    // t is the node that roots the subtree.    
    bool contains( const C & x, BinaryNode* t ) const
    {
        if( t == nullptr )
            return false;
        else if( x < t->element )
            return contains( x, t->left );
        else if( t->element < x )
            return contains( x, t->right );
        else
            return true;    // Match
    }

    void makeEmpty( BinaryNode* & t )
    {
        if( t != nullptr )
        {
            makeEmpty( t->left );
            makeEmpty( t->right );
            delete t;
        }
        t = nullptr;
    }

    void printTree( BinaryNode* t) const
    {
        if( t != nullptr )
        {
            printTree( t->left);
            cout << t->element << " - ";
            printTree( t->right);
        }
    }
};
#endif

:Program your own file lab07.cpp in which your main() function will test the new data structure.

  • The main function is contained in the file lab07.cpp.
  • Declare an instance of BinarySearchTree (short: BST) suitable to hold integer values.
  • Prompt user to enter a random sequence of integer values, insert these values into the data structure (the entered values should NOT be in sorted order).
  • Call the printTree() member function in order to print out the values of the BST structure.
  • Prompt user to enter a random sequence of integer values, remove these values from your BST. Print out the reduced BST.
  • Add the following member function in your BinarySearchTree class template.
    public:
    
    void printInternal() 
    {
       print_Internal(root,0);
    }
    
    private:
    
    void printInternal(BinaryNode* t, int offset)
    {
       if (t == nullptr)
           return;
    
       for(int i = 1; i <= offset; i++) 
           cout << "...";
       cout << t->element << endl;
       printInternal(t->left, offset + 1);
       printInternal(t->right, offset + 1);
    }
    
  • Go back to your program lab07.cpp and call printInternal. Compile and run your program, and see what you get.

The expected result:

insert the values (stop when entering 0):
10 5 20 3 22 6 18 7 9 13 15 4 2 1 19 30 8 0
print the values:
1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 13 - 15 - 18 - 19 - 20 - 22 - 30 - 
Print the tree:
10
...5
......3
.........2
............1
.........4
......6
.........7
............9
...............8
...20
......18
.........13
............15
.........19
......22
.........30
remove the values (stop when entering 0):
1 11 2 12 3 13 0
print the values:
4 - 5 - 6 - 7 - 8 - 9 - 10 - 15 - 18 - 19 - 20 - 22 - 30 - 
Print the tree:
10
...5
......4
......6
.........7
............9
...............8
...20
......18
.........15
.........19
......22
.........30

Solutions

Expert Solution

Below is the C++ code I hope that i have provided sufficient comments for your better understanding Note that I have done proper indentation but this code is automatically left alligned on this interface

#include<bits/stdc++.h>
#include "BinarySearch.h"
using namespace std;
int main()
{
    BinarySearchTree <int>tree;
    string s,num;
    stringstream ss;
    int temp;
    cout<<"insert the values (stop when entering 0):\n";
    getline(cin,s); //Take input in string format
    int prev=-1,ind=-1;
    while(1)
    {
        prev=ind;
        ind=s.find(" ",prev+1); //find index of next space
        if(ind==-1) //we reached last word
            break;   //exit from loop
        num=s.substr(prev+1,ind-prev-1); //num contains number in string format
        //convert num from string to integer
        ss<<num;
        ss>>temp;
        ss.clear();
        tree.insert(temp); //add number to tree
    }
    cout<<"print the values:\n";
    tree.printTree();
    cout<<"\nPrint the tree:\n";
    tree.printInternal();
    cout<<"\nremove the values (stop when entering 0):\n";
    getline(cin,s); //Take input in string format
    prev=-1,ind=-1;
    while(1)
    {
        prev=ind;
        ind=s.find(" ",prev+1); //find index of next space
        if(ind==-1) //we reached last word
            break;   //exit from loop
        num=s.substr(prev+1,ind-prev-1); //num contains number in string format
        //convert num from string to integer
        ss<<num;
        ss>>temp;
        ss.clear();
        tree.remove(temp); //add number to tree
    }
    cout<<"\nprint the values:\n";
    tree.printTree();
    cout<<"\nPrint the tree:\n";
    tree.printInternal();
    return 0;
}

Below is the screenshot of output

I have tried to explain it in very simple language and I hope that i have answered your question satisfactorily.Leave doubts in comment section if any.


Related Solutions

In C++ prototype functions above "main" and define them below "main"; Write a program that uses...
In C++ prototype functions above "main" and define them below "main"; Write a program that uses two identical arrays of at least 20 integers. It should call a function that uses the bubble sort algorithm to sort one of the arrays in ascending order. The function should keep count of the number of exchanges it makes. The program then should call a function that uses the selection sort algorithm to sort the other arrays. It should also keep count of...
IN C++, ONE FILE Also include the main class that just runs these functions, thanks. Write...
IN C++, ONE FILE Also include the main class that just runs these functions, thanks. Write a recursive function to produce a pattern of n lines of asterisks. The first line contains one asterisk, the next line contains two, and so on, up to the nth line, which contains n asterisks. For example, if the non-negative integer is 5, the pattern generated is: * ** *** **** ***** Prototype: void pattern(unsigned n); Write a recursive function, sum_range that finds the...
(i just need an answer for question 4) (i just need an answer for just question...
(i just need an answer for question 4) (i just need an answer for just question 4) you have two facilities, one in Malaysia and one in Indonesia. The variable cost curve in the Malaysian plant is described as follows: VCM = q­ + .0005*q2 , where q is quantity produced in that plant per month. The variable cost curve in the Indonesian plant is described by VCI = .5q + .00075q2, where q is the quantity produced in that...
C++ Need to add the following functions to my templatized class linked list. (main is already...
C++ Need to add the following functions to my templatized class linked list. (main is already set to accommodate the functions below) --void destroy_list () deletes each node in the list, and resets the header to nullptr --bool search_list (key value) searches the list for a node with the given key. Returns true if found, false if not. --bool delete_node (key value) deletes the node which contains the given key. If there is more than one node with the same...
IN JAVA PLEASE ASAP !!! I just need the main and mergesort function Ask the user...
IN JAVA PLEASE ASAP !!! I just need the main and mergesort function Ask the user for the number of elements, not to exceed arraySize = 20 (put appropriate input validation) Ask the user for the type of data they will enter - EnglishGrade or MathGrade objects. Use your EnglishGrade and MathGrade classes Based on the input, create an appropriate array for the data to be entered. Write a helper function called recursionMergeSort such that: It is a standalone function...
I need to know the steps of solution for part (b,c,d) I have been trying for...
I need to know the steps of solution for part (b,c,d) I have been trying for almost 2 days. A 195 -keV X-ray photon coherently scatters off one of the valence electrons of a nitrogen atom. Assume that the scattering angle of the photon is ? = 15
Assume the following functions have already been defined, write a main() using c++ that uses them...
Assume the following functions have already been defined, write a main() using c++ that uses them to fill a vector with random integers, remove the smallest and largest integers from the vector, save the result in a file called "trimmed.txt" void fillRandom(vector & nums, int howMany); // fill with specified number of integers int minValue(vector nums); // return smallest value in vector int maxValue(vector <;int> nums); // return largest value in vector void writeFile(string outFileName, vector nums ); // writes...
i just need the national saving rate for the last two, b and c, I answered...
i just need the national saving rate for the last two, b and c, I answered everything else by myself and i just need the national saving for B and C In each part that follows, use the economic data given to find national saving, private saving, public saving, and the national saving rate. a. Household saving = 200     Business saving = 400      Government purchases of goods and services = 100      Government transfers and interest payments = 100      Tax collections...
Can someone explain a,b and c? The answers are correct I believe but I just need...
Can someone explain a,b and c? The answers are correct I believe but I just need a more clear explenation on the formulas and final answers If 2 cards are drawn from a well-shuffled deck of 52 playing cards, what are the probabilities of getting Answer: Total no of ways of drawing 2 cards from a well-shuffled deck of 52 playing cards = 52C2 = 1326 (a)        two spades; Number of ways getting 2 spades / total number of ways...
Write this in java please. I use Eclipse Write the following two functions. main doesnt need...
Write this in java please. I use Eclipse Write the following two functions. main doesnt need to be filled up. Function 1: Write a function called howMany that takes two arguments: an array of integers called arr, and an integer called iTarget. The function should return an integer result. Inside the function write a loop to go through the array and count the number of elements in the array that have the same value as iTarget. At the end it...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT