Question

In: Computer Science

In C++, create a class to hold a set of strings called setTree. setTrees contain copies...

In C++, create a class to hold a set of strings called setTree. setTrees contain copies of the strings inserted so that the strings cannot be changed due to the fact that changing the strings inside the set could break the binary search tree. The strings are case sensitive.

TreeSet implements the following:

bool add(const string& s) -- add s to the set, if it's not already there. Return true if the set changed, false otherwise.

void clear() -- remove all elements from the set

bool contains(const string& s) const -- test whether or not s is in the set.

bool isEmpty() const -- test whether or not the set is empty

bool remove(const string& s) -- remove s from the set, if it was there. Return true if the set changed, false otherwise.

int size() const -- return the number of strings in set.

int toArray(string sa[]) const -- put the elements of the set into the array sa. Assume that sa has sufficient room (it's the client's responsibility to check). You can place the strings in any order you choose.

The class also includes a zero-argument constructor to create an empty set, a constructor that takes in an array of strings and its size (creating a set containing each element of the array), copy constructor, assignment operator, and destructor. The copy constructor and assignment operator make deep copies.

setTree implements the set using a binary search tree. The tree does not need to be balanced. The implementation of the tree node class is hidden from the client. There are no memory leaks.

Solutions

Expert Solution

Classes:

/*
 * TreeSetNode 
 * It represents the node inside the Binary Search Tree (BST)
 */
class TreeSetNode
{
public:
    string s;
    TreeSetNode *left; /* left child of the BST */
    TreeSetNode *right; /* right child of the BST */

    TreeSetNode(const string _s) {
        s = _s;
        left = nullptr;
        right = nullptr;
    }
};

class TreeSet
{
public:
    /* head points to the root of the BST*/
    TreeSetNode *head;
    /* _size represents the current number of nodes of the BST */
    int _size;

    TreeSet() {
        head = nullptr;
        _size = 0;
    }
    TreeSet(string s[] , int size) {
        head = nullptr;
        for(int i = 0 ; i < size; i++) {
            add(s[i]);
        }
        _size = size;
    }
    TreeSet(TreeSet &sTree) {
        _size = sTree._size;
        head = buildTree(sTree.head);
    }
    ~TreeSet() {
        clear();
    }
    TreeSetNode* buildTree(TreeSetNode *toCopyFrom) {
        if(toCopyFrom == nullptr) {
            return nullptr;
        }
        TreeSetNode *root = new TreeSetNode(toCopyFrom->s);
        root->left = buildTree(toCopyFrom->left);
        root->right = buildTree(toCopyFrom->right);
        return root;
    }
    bool add(const string& s , TreeSetNode *root) {
        if(root->s == s) {
            /*
             * If s is already present, we will return false as we would not change the set. 
             */
            return false;
        }
        if(root->s < s) {
            if(root->right == nullptr) {
                root->right = new TreeSetNode(s);
                _size++;
                return true;
            } else {
                return add(s , root->right);
            }
        } else {
            if(root->left == nullptr) {
                root->left = new TreeSetNode(s);
                _size++;
                return true;
            } else {
                return add(s , root->left);
            }
        }
    }
    /*
    *  add s to the set, if it's not already there. Return true if the set changed, false otherwise.
    * */
    bool add(const string& s) {
        if(head == nullptr) {
            head = new TreeSetNode(s);
            return true;
        }
        /*
         * overloaded function add(string, TreeSetNode*) 
         * will be called which would take care of addition 
         * of the string in the set.
         */
        return add(s , head);
    }
    void clear(TreeSetNode *root) {
        if(root == nullptr) {
            return ;
        }
        /*
        * We would delete a node's left subtree , then the right sub tree and then would free the node
        * */
        clear(root->left);
        clear(root->right);
        free(root); 
    }
    /*
     * remove all elements from the set
     * */
    void clear() {
        clear(head);
        head = nullptr;
        _size = 0;
    }
    
    bool contains(const string &s , TreeSetNode *root) const {
        if(root == nullptr) {
            return false;
        }
        if(root->s == s) {
            return true;
        } else if(root->s < s) {
            return contains(s , root->right);
        } else {
            return contains(s , root->left);
        }
    }

    /*
    * test whether or not s is in the set.
    * */
    bool contains(const string& s) const {
        return contains(s , head);
    }
    bool isEmpty() const {
        return (_size==0);
    }
    TreeSetNode* removeNode(const string& s , TreeSetNode *root) {
        if(root->s == s) {
            if(root->left == nullptr && root->right == nullptr) {
                free(root);
                _size--;
                return nullptr;
            } else if(root->left == nullptr) {
                return root->right;
            } else if(root->right == nullptr) {
                return root->left;
            } else {
                TreeSetNode *lt = root->left;
                while(lt->right != nullptr) {
                    lt = lt->right;
                }
                root->s = lt->s;
                lt->s = s;
                root->left = removeNode(s , root->left);
                return root;
            }
        } else if(root->s < s) {
            root->right = removeNode(s , root->right);
        } else {
            root->left = removeNode(s , root->left);
        }
        return root;
    }
    /*
    * remove s from the set, if it was there. Return true if the set changed, false otherwise.
    * */
    bool remove(const string& s)  {
        if(!contains(s)) {
            return false;
        }
        head = removeNode(s , head);
        return true;
    }
    int size() const {
        return _size;
    }
    void toArray(TreeSetNode *root , string sa[] , int &i) const {
        if(root == nullptr) {
            return ;
        }
        toArray(root->left , sa , i);
        sa[i++] = root->s;
        toArray(root->right , sa , i);
    }
    int toArray(string sa[]) const {
        int i = 0 ;
        toArray(head , sa , i);
        return _size;
    }
};

I had also written a main function to test some functionalities of the above class..

int main() {

    /* Test 1 */
    string arr[6] = {"akash" , "panda" , "aa" , "as" , "sss" , "err"};
    TreeSet s_tree(arr , 6);
    string s_tree_arr[6];
    int sz = s_tree.toArray(s_tree_arr);
    cout << "Printing the contents of the Set :" << endl; 
    for(int i=0 ; i < 6 ; i++) {
        cout << s_tree_arr[i] << endl;
    }
    cout << "------------------------------------" << endl;
    cout << "Removing panda from the set" << endl;
    bool removed = s_tree.remove("panda");
    cout << "Removed" << endl;
    cout << "Printing the contents of the Set Again:" << endl; 
    sz = s_tree.toArray(s_tree_arr);
    for(int i=0 ; i < sz ; i++) {
        cout << s_tree_arr[i] << endl;
    }
    cout << "------------------------------------" << endl;
    cout << "Making use of the copy constructor" << endl;
    TreeSet new_stree = s_tree;
    sz = new_stree.toArray(s_tree_arr);
    cout << "Printing the contents of the new set:" << endl; 
    for(int i=0 ; i < sz ; i++) {
        cout << s_tree_arr[i] << endl;
    }
    cout << "------------------------------------" << endl;
    return 0;
}


The complete file of the class along with the main function is given below:
Paste the below mentioned conents to settree.cpp file.

#include<bits/stdc++.h>
using namespace std;

/*
 * TreeSetNode 
 * It represents the node inside the Binary Search Tree (BST)
 */
class TreeSetNode
{
public:
    string s;
    TreeSetNode *left; /* left child of the BST */
    TreeSetNode *right; /* right child of the BST */

    TreeSetNode(const string _s) {
        s = _s;
        left = nullptr;
        right = nullptr;
    }
};

class TreeSet
{
public:
    /* head points to the root of the BST*/
    TreeSetNode *head;
    /* _size represents the current number of nodes of the BST */
    int _size;

    TreeSet() {
        head = nullptr;
        _size = 0;
    }
    TreeSet(string s[] , int size) {
        head = nullptr;
        for(int i = 0 ; i < size; i++) {
            add(s[i]);
        }
        _size = size;
    }
    TreeSet(TreeSet &sTree) {
        _size = sTree._size;
        head = buildTree(sTree.head);
    }
    ~TreeSet() {
        clear();
    }
    TreeSetNode* buildTree(TreeSetNode *toCopyFrom) {
        if(toCopyFrom == nullptr) {
            return nullptr;
        }
        TreeSetNode *root = new TreeSetNode(toCopyFrom->s);
        root->left = buildTree(toCopyFrom->left);
        root->right = buildTree(toCopyFrom->right);
        return root;
    }
    bool add(const string& s , TreeSetNode *root) {
        if(root->s == s) {
            /*
             * If s is already present, we will return false as we would not change the set. 
             */
            return false;
        }
        if(root->s < s) {
            if(root->right == nullptr) {
                root->right = new TreeSetNode(s);
                _size++;
                return true;
            } else {
                return add(s , root->right);
            }
        } else {
            if(root->left == nullptr) {
                root->left = new TreeSetNode(s);
                _size++;
                return true;
            } else {
                return add(s , root->left);
            }
        }
    }
    /*
    *  add s to the set, if it's not already there. Return true if the set changed, false otherwise.
    * */
    bool add(const string& s) {
        if(head == nullptr) {
            head = new TreeSetNode(s);
            return true;
        }
        /*
         * overloaded function add(string, TreeSetNode*) 
         * will be called which would take care of addition 
         * of the string in the set.
         */
        return add(s , head);
    }
    void clear(TreeSetNode *root) {
        if(root == nullptr) {
            return ;
        }
        /*
        * We would delete a node's left subtree , then the right sub tree and then would free the node
        * */
        clear(root->left);
        clear(root->right);
        free(root); 
    }
    /*
     * remove all elements from the set
     * */
    void clear() {
        clear(head);
        head = nullptr;
        _size = 0;
    }
    
    bool contains(const string &s , TreeSetNode *root) const {
        if(root == nullptr) {
            return false;
        }
        if(root->s == s) {
            return true;
        } else if(root->s < s) {
            return contains(s , root->right);
        } else {
            return contains(s , root->left);
        }
    }

    /*
    * test whether or not s is in the set.
    * */
    bool contains(const string& s) const {
        return contains(s , head);
    }
    bool isEmpty() const {
        return (_size==0);
    }
    TreeSetNode* removeNode(const string& s , TreeSetNode *root) {
        if(root->s == s) {
            if(root->left == nullptr && root->right == nullptr) {
                free(root);
                _size--;
                return nullptr;
            } else if(root->left == nullptr) {
                return root->right;
            } else if(root->right == nullptr) {
                return root->left;
            } else {
                TreeSetNode *lt = root->left;
                while(lt->right != nullptr) {
                    lt = lt->right;
                }
                root->s = lt->s;
                lt->s = s;
                root->left = removeNode(s , root->left);
                return root;
            }
        } else if(root->s < s) {
            root->right = removeNode(s , root->right);
        } else {
            root->left = removeNode(s , root->left);
        }
        return root;
    }
    /*
    * remove s from the set, if it was there. Return true if the set changed, false otherwise.
    * */
    bool remove(const string& s)  {
        if(!contains(s)) {
            return false;
        }
        head = removeNode(s , head);
        return true;
    }
    int size() const {
        return _size;
    }
    void toArray(TreeSetNode *root , string sa[] , int &i) const {
        if(root == nullptr) {
            return ;
        }
        toArray(root->left , sa , i);
        sa[i++] = root->s;
        toArray(root->right , sa , i);
    }
    int toArray(string sa[]) const {
        int i = 0 ;
        toArray(head , sa , i);
        return _size;
    }
};

int main() {

    /* Test 1 */
    string arr[6] = {"akash" , "panda" , "aa" , "as" , "sss" , "err"};
    TreeSet s_tree(arr , 6);
    string s_tree_arr[6];
    int sz = s_tree.toArray(s_tree_arr);
    cout << "Printing the contents of the Set :" << endl; 
    for(int i=0 ; i < 6 ; i++) {
        cout << s_tree_arr[i] << endl;
    }
    cout << "------------------------------------" << endl;
    cout << "Removing panda from the set" << endl;
    bool removed = s_tree.remove("panda");
    cout << "Removed" << endl;
    cout << "Printing the contents of the Set Again:" << endl; 
    sz = s_tree.toArray(s_tree_arr);
    for(int i=0 ; i < sz ; i++) {
        cout << s_tree_arr[i] << endl;
    }
    cout << "------------------------------------" << endl;
    cout << "Making use of the copy constructor" << endl;
    TreeSet new_stree = s_tree;
    sz = new_stree.toArray(s_tree_arr);
    cout << "Printing the contents of the new set:" << endl; 
    for(int i=0 ; i < sz ; i++) {
        cout << s_tree_arr[i] << endl;
    }
    cout << "------------------------------------" << endl;
    return 0;
}



Steps to Compile:
g++ settree.cpp -o settree.out

How to run:
./settree.out

Sample output:

Printing the contents of the Set :
aa
akash
as
err
panda
sss
------------------------------------
Removing panda from the set
Removed
Printing the contents of the Set Again:
aa
akash
as
err
sss
------------------------------------
Making use of the copy constructor
Printing the contents of the new set:
aa
akash
as
err
sss
------------------------------------

Related Solutions

Create a class called Sphere. The class will contain the following    Instance data double radius...
Create a class called Sphere. The class will contain the following    Instance data double radius Methods Constructor with one parameter which will be used to set the radius instance data Getter and Setter for radius             Area - calculate the area of the sphere (4 * PI * radius * radius)             Volume - calculate and return the volume of the sphere (4/3 * PIE * radius * radius * radius) toString - returns a string with the...
Using Java: Create a class that will hold the information about a clock, called Clock. You...
Using Java: Create a class that will hold the information about a clock, called Clock. You need to keep minutes, hours and seconds in military time (24-hour) format. Include member functions that will setTime ( this will set the hours, minutes and seconds of the clock), getHours (return the hours), getMinutes (return the minutes) and getSeconds (return the seconds). Another method printTime which will print the time out like this 03:13:09 (hours:minutes:seconds). Overloaded constructors that will take in hours, minutes...
C++ Define a base class called Person. The class should have two data members to hold...
C++ Define a base class called Person. The class should have two data members to hold the first name and last name of a person, both of type string. The Person class will have a default constructor to initialize both data members to empty strings, a constructor to accept two string parameters and use them to initialize the first and last name, and a copy constructor. Also include appropriate accessor and mutator member functions. Overload the operators == and !=...
c++ Create a class named EvolutionTree which will hold a list of species and their expected...
c++ Create a class named EvolutionTree which will hold a list of species and their expected age, and allow a user to search for a particular species or an age. EvolutionTree should have private data members: species (a string array of size 400 with all the species) speciesAges (an int array of size 400 for all the species' ages). EvolutionTree should have a default constructor which should initialize the species array to empty strings ("") and initialize the speciesAges array...
In object C Define a class called XYPoint that will hold a Cartesian coordinate (x, y),...
In object C Define a class called XYPoint that will hold a Cartesian coordinate (x, y), where x and y are integers. Define methods to individually set the x and y coordinates of your new point and retrieve their values. Write an Objective-C program to implement your new class and test it (main section of the file). Your test program needs to create two instances of your class. Make sure your program test prints out the values that you have...
Define a class called Goals that has the following requirements in c++: a function called set...
Define a class called Goals that has the following requirements in c++: a function called set that takes 3 int parameters that are goals for "fame", "happiness" and "money". The function returns true and saves the values if they add up to exactly 60, and returns false otherwise (you may assume the parameters are not negative) a functions satisfies that takes 3 int parameters and returns true if each parameter is at least as large as the saved goal, false...
Create a Class to contain a customer order Create attributes of that class to store Company...
Create a Class to contain a customer order Create attributes of that class to store Company Name, Address and Sales Tax. Create a public property for each of these attributes. Create a class constructor without parameters that initializes the attributes to default values. Create a class constructor with parameters that initializes the attributes to the passed in parameter values. Create a behavior of that class to generate a welcome message that includes the company name. Create a Class to contain...
In C++, implement a class called setOper that provides several simple set operations. The class only...
In C++, implement a class called setOper that provides several simple set operations. The class only needs to deal with sets that are closed intervals specified by two real numbers; for example, the pair (2.5, 4.5) represent the interval [2.5, 4.5]. The following operations should be supported: - Check if the value x belongs to the given interval. - Check if the value x belongs to the intersection of two intervals. - Check if the value x belongs to the...
Class Instructions You will create a password verification program using C-strings and character testing. The user...
Class Instructions You will create a password verification program using C-strings and character testing. The user will enter a password as a C-string. (Character array). You must test that the password contains at least: One lowercase letter One uppercase letter One number (0-9) The password can contain no spaces You are to add one more requirement to the password. I need help in setting this program up. #include <iostream> #include <cctype> using namespace std; int main() { char input; cout...
Needed in C++ In this assignment, you are asked to create a class called Account, which...
Needed in C++ In this assignment, you are asked to create a class called Account, which models a bank account. The requirement of the account class is as follows (1) It contains two data members: accountNumber and balance, which maintains the current account name and balance, respectively. (1) It contains three functions: functions credit() and debit(), which adds or subtracts the given amount from the balance, respectively. The debit() function shall print ”amount withdrawn exceeds the current balance!” if the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT