Question

After the header, each line of the database file rebase210.txt contains the name of a restriction...

After the header, each line of the database file rebase210.txt contains the name of a restriction enzyme and possible DNA sites the enzyme may cut (cut location is indicated by a ‘) in the following format: enzyme_acronym/recognition_sequence/…/recognition_sequence//

For instance the first few lines of rebase210.txt are: AanI/TTA'TAA// AarI/CACCTGCNNNN'NNNN/'NNNNNNNNGCAGGTG// AasI/GACNNNN'NNGTC// AatII/GACGT'C// AbsI/CC'TCGAGG// AccI/GT'MKAC// AccII/CG'CG// AccIII/T'CCGGA// Acc16I/TGC'GCA// Acc36I/ACCTGCNNNN'NNNN/'NNNNNNNNGCAGGT// …

That means that each line contains one enzyme acronym associated with one or more recognition sequences. For example on line 2:The enzyme acronym AarI corresponds to the two recognition sequences CACCTGCNNNN'NNNN and 'NNNNNNNNGCAGGTG.

Part (a) You will create a parser to read in this database and construct an AVL tree. For each line of the database and for each recognition sequence in that line, you will create a new SequenceMap object that contains the recognition sequence as its recognition_sequence_ and the enzyme acronym as the only string of its enzyme_acronyms_, and you will insert this object into the tree. This is explained with the following pseudo code:

Tree<SequenceMap> a_tree; string db_line; // Read the file line-by-line:

while (GetNextLineFromDatabaseFile(db_line)) {

// Get the first part of the line:

string an_enz_acro = GetEnzymeAcronym(db_line); string a_reco_seq; while (GetNextRegocnitionSequence(db_line, a_rego_seq){ SequenceMap new_sequence_map(a_reco_seq, an_enz_acro); a_tree.insert(new_sequence_map); } }

In the case that the new_sequence_map.recognition_sequence_ equals the recognition_sequence_ of a node X in the tree, then the search tree’s insert() function will call the X.Merge(new_sequence_map) function of the existing element. This will have the effect of updating the enzyme_acronym_ of X. Note, that this will be part of the functionality of the insert() function. The Merge() will only be called in case of duplicates as described above. Otherwise, no Merge() is required and the new_sequence_map will be inserted into the tree. To implement the above, write a test program named query_tree which will use your parser to create a search tree and then allow the user to query it using a recognition sequence. If that sequence exists in the tree then this routine should print all the corresponding enzymes that correspond to that recognition sequence. Your programs should run from the terminal as follows: The user should enter THREE strings (supposed to be recognition sequences) for instance:

CC'TCGAGG

TTA'TAA

TC'C

Your program should print in the standard output their associated enzyme acronyms. In the above example the output will be

AbsI

AanI PsiI

Not Found

I will test it with a file containing three strings and run your code like that: To make things easier the following is the already written SequenceMap class to which this part is related with

#ifndef SEQUENCEMAP_H
#define SEQUENCEMAP_H

class SequenceMap {
public:
  
SequenceMap() = default;
SequenceMap(const SequenceMap &rhs) = default;
SequenceMap& operator=(const SequenceMap &rhs) = default;
SequenceMap(SequenceMap &&rhs) = default;
SequenceMap& operator=(SequenceMap &&rhs) = default;
~SequenceMap() = default;
SequenceMap(const string &a_rec_seq, const string &an_enz_acro) {
recognition_sequence_ = a_rec_seq;
enzyme_acronyms_.push_back(an_enz_acro);
}

bool operator<(const SequenceMap &rhs) const {
return (recognition_sequence_ < rhs.recognition_sequence_);
}
friend std::ostream &operator<<(std::ostream &out, const SequenceMap &a_SequenceMap) {
out << a_SequenceMap.recognition_sequence_ << " ";
for (int i = 0; i < a_SequenceMap.enzyme_acronyms_.size(); ++i) {
out << a_SequenceMap.enzyme_acronyms_[i] << " ";
}
return out;
}
void Merge(const SequenceMap &other_sequence) {
for (int i = 0; i < other_sequence.enzyme_acronyms_.size(); ++i) {
enzyme_acronyms_.push_back(other_sequence.enzyme_acronyms_[i]);
}
}

private:
string recognition_sequence_ ;
vector<string> enzyme_acronyms_;
};

#endif

And here is the avl_tree.h to whcih you have to insert.

#ifndef AVL_TREE_H
#define AVL_TREE_H

template <typename Comparable>
class AvlTree
{
public:
AvlTree( ) : root{ nullptr }
{ }
  
AvlTree( const AvlTree & rhs ) : root{ nullptr }
{
root = clone( rhs.root );
}

AvlTree( AvlTree && rhs ) : root{ rhs.root }
{
rhs.root = nullptr;
}
  
~AvlTree( )
{
makeEmpty( );
}

/**
* Deep copy.
*/
AvlTree & operator=( const AvlTree & rhs )
{
AvlTree copy = rhs;
std::swap( *this, copy );
return *this;
}
  
/**
* Move.
*/
AvlTree & operator=( AvlTree && rhs )
{
std::swap( root, rhs.root );
  
return *this;
}
  
/**
* Find the smallest item in the tree.
*/
const Comparable & findMin( ) const
{
if( isEmpty( ) )
throw UnderflowException{ };
return findMin( root )->element;
}

/**
* Find the largest item in the tree.
*/
const Comparable & findMax( ) const
{
if( isEmpty( ) )
throw UnderflowException{ };
return findMax( root )->element;
}

/**
* Returns true if x is found in the tree.
*/
bool contains( const Comparable & x ) const
{
return contains( x, root );
}
void insert( const Comparable & x )
{
insert( x, root );
}

/**
* Insert x into the tree; duplicates are ignored.
*/
void insert( Comparable && x )
{
insert( std::move( x ), root );
}

private:
struct AvlNode
{
Comparable element;
AvlNode *left;
AvlNode *right;
int height;

AvlNode( const Comparable & ele, AvlNode *lt, AvlNode *rt, int h = 0 )
: element{ ele }, left{ lt }, right{ rt }, height{ h } { }
  
AvlNode( Comparable && ele, AvlNode *lt, AvlNode *rt, int h = 0 )
: element{ std::move( ele ) }, left{ lt }, right{ rt }, height{ h } { }
};

AvlNode *root;
/**
* Internal method to insert into a subtree.
*/
void insert( const Comparable & x, AvlNode * & t )
{
if( t == nullptr )
t = new AvlNode{ x, nullptr, nullptr };
else if( x < t->element )
insert( x, t->left );
else if( t->element < x )
insert( x, t->right );
  
balance( t );
}

/**
* Internal method to insert into a subtree.
*/
void insert( Comparable && x, AvlNode * & t )
{
if( t == nullptr )
t = new AvlNode{ std::move( x ), nullptr, nullptr };
else if( x < t->element )
insert( std::move( x ), t->left );
else if( t->element < x )
insert( std::move( x ), t->right );
  
balance( t );
}

static const int ALLOWED_IMBALANCE = 1;

// Assume t is balanced or within one of being balanced
void balance( AvlNode * & t )
{
if( t == nullptr )
return;
  
if( height( t->left ) - height( t->right ) > ALLOWED_IMBALANCE ) {
if( height( t->left->left ) >= height( t->left->right ) )
rotateWithLeftChild( t );
else
doubleWithLeftChild( t );
} else if( height( t->right ) - height( t->left ) > ALLOWED_IMBALANCE ) {
if( height( t->right->right ) >= height( t->right->left ) )
rotateWithRightChild( t );
else
doubleWithRightChild( t );
   }
t->height = max( height( t->left ), height( t->right ) ) + 1;
}
  
/**
* Internal method to find the smallest item in a subtree t.
*/
AvlNode * findMin( AvlNode *t ) const
{
if( t == nullptr )
return nullptr;
if( t->left == nullptr )
return t;
return findMin( t->left );
}
AvlNode * findMax( AvlNode *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.
*/
bool contains( const Comparable & x, AvlNode *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
}

int height( AvlNode *t ) const
{
return t == nullptr ? -1 : t->height;
}
void rotateWithLeftChild( AvlNode * & k2 )
{
AvlNode *k1 = k2->left;
k2->left = k1->right;
k1->right = k2;
k2->height = max( height( k2->left ), height( k2->right ) ) + 1;
k1->height = max( height( k1->left ), k2->height ) + 1;
k2 = k1;
}
void doubleWithLeftChild( AvlNode * & k3 )
{
rotateWithRightChild( k3->left );
rotateWithLeftChild( k3 );
}

};

#endif

// <Your name>
// Main file for Part2(a) of Homework 2.

#include "avl_tree.h"
#include "sequence_map.h"
#include <iostream>
#include <string>
using namespace std;

namespace {

// @db_filename: an input filename.
// @a_tree: an input tree of the type TreeType. It is assumed to be
// empty.
template <typename TreeType>
void QueryTree(const string &db_filename, TreeType &a_tree) {
while (GetNextLineFromDatabaseFile(db_line)) {

// Get the first part of the line:

string an_enz_acro = GetEnzymeAcronym(db_line); string a_reco_seq; while (GetNextRegocnitionSequence(db_line, a_rego_seq){ SequenceMap new_sequence_map(a_reco_seq, an_enz_acro); a_tree.insert(new_sequence_map); } // End second while.

                                       }

// End first while.
// Code for running Part2(a)
// You can use public functions of TreeType. For example:
a_tree.insert(10);
a_tree.printTree();
}

} // namespace

int main(int argc, char **argv) {
if (argc != 2) {
cout << "Usage: " << argv[0] << " <databasefilename>" << endl;
return 0;
}
const string db_filename(argv[1]);
cout << "Input filename is " << db_filename << endl;
// Note that you will replace AvlTree<int> with AvlTree<SequenceMap>
AvlTree<int> a_tree;
QueryTree(db_filename, a_tree);
return 0;
}

Thank you so much. pretty much most of the code is written but please help me with the parser and insertion. thank you.  Plz make any needed changes to the existing code.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

AvlTree.h

#ifndef AVL_TREE_H
#define AVL_TREE_H

#include "dsexceptions.h"
#include <algorithm>
#include <iostream>
using namespace std;

// AvlTree class
//
// CONSTRUCTION: zero parameter
//
// ******************PUBLIC OPERATIONS*********************
// void insert( x )       --> Insert x
// void remove( x )       --> Remove x (unimplemented)
// bool contains( x )     --> Return true if x is present
// Comparable findMin( ) --> Return smallest item
// Comparable findMax( ) --> Return largest item
// boolean isEmpty( )     --> Return true if empty; else false
// void makeEmpty( )      --> Remove all items
// void printTree( )      --> Print tree in sorted order
// ******************ERRORS********************************
// Throws UnderflowException as warranted

template <typename Comparable>
class AvlTree
{
public:
    AvlTree( ) : root{ nullptr }
      { }
  
    AvlTree( const AvlTree & rhs ) : root{ nullptr }
    {
        root = clone( rhs.root );
    }

    AvlTree( AvlTree && rhs ) : root{ rhs.root }
    {
        rhs.root = nullptr;
    }
  
    ~AvlTree( )
    {
        makeEmpty( );
    }

    /**
     * Deep copy.
     */
    AvlTree & operator=( const AvlTree & rhs )
    {
        AvlTree copy = rhs;
        std::swap( *this, copy );
        return *this;
    }
      
    /**
     * Move.
     */
    AvlTree & operator=( AvlTree && rhs )
    {
        std::swap( root, rhs.root );
      
        return *this;
    }
  
    /**
     * Find the smallest item in the tree.
     * Throw UnderflowException if empty.
     */
    const Comparable & findMin( ) const
    {
        if( isEmpty( ) )
            throw UnderflowException{ };
        return findMin( root )->element;
    }

    /**
     * Find the largest item in the tree.
     * Throw UnderflowException if empty.
     */
    const Comparable & findMax( ) const
    {
        if( isEmpty( ) )
            throw UnderflowException{ };
        return findMax( root )->element;
    }

    /**
     * Test if the tree is logically empty.
     * Return true if empty, false otherwise.
     */
    bool isEmpty( ) const
    {
        return root == nullptr;
    }

    /**
     * Print the tree contents in sorted order.
     */
    void printTree( ) const
    {
        if( isEmpty( ) )
            cout << "Empty tree" << endl;
        else
            printTree( root );
    }

    /**
     * Make the tree logically empty.
     */
    void makeEmpty( )
    {
        makeEmpty( root );
    }

    /**
     * Insert x into the tree; duplicates are ignored.
     */
    void insert( const Comparable & x )
    {
        insert( x, root );
    }
   
    /**
     * Insert x into the tree; duplicates are ignored.
     */
    void insert( Comparable && x )
    {
        insert( std::move( x ), root );
    }

    /**
     * Returns true if x is found in the tree.
     */
    bool contains( const Comparable & x ) const {
        return contains( x, root );
    }


    /*****************************************************/
    // START OF ASSIGNMENT 2:

    void search( const Comparable & x ) {
        search( x, root );
    }
    int numOfNodes() {
        return numOfNodes(root);
    }
    float numOfPaths() {
        float pathTracker = 0;
        return numOfPaths(root, pathTracker);
    }
    bool contains( const Comparable & x, float &recursionCalls) {
        return contains( x, root, recursionCalls);
    }
    void remove(const Comparable & x, float &recursionCalls, bool &removedNode) {
        remove(x, root, recursionCalls, removedNode);
    }

    //END OF ASSIGNMENT 2
    /*****************************************************/


private:
    struct AvlNode
    {
        Comparable element;
        AvlNode   *left;
        AvlNode   *right;
        int       height;

        AvlNode( const Comparable & ele, AvlNode *lt, AvlNode *rt, int h = 0 )
          : element{ ele }, left{ lt }, right{ rt }, height{ h } { }
      
        AvlNode( Comparable && ele, AvlNode *lt, AvlNode *rt, int h = 0 )
          : element{ std::move( ele ) }, left{ lt }, right{ rt }, height{ h } { }
    };

    AvlNode *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 Comparable & x, AvlNode * & t )
    {
        if( t == nullptr )
            t = new AvlNode{ x, nullptr, nullptr };
        else if( x < t->element )
            insert( x, t->left );
        else if( t->element < x )
            insert( x, t->right );
        else
            t->element.Merge(x);
      
        balance( t );
    }

    /**
     * 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( Comparable && x, AvlNode * & t )
    {
        if( t == nullptr )
            t = new AvlNode{ std::move( x ), nullptr, nullptr };
        else if( x < t->element )
            insert( std::move( x ), t->left );
        else if( t->element < x )
            insert( std::move( x ), t->right );
        else
            t->element.Merge(x);
      
        balance( t );
    }
   

  
    static const int ALLOWED_IMBALANCE = 1;

    // Assume t is balanced or within one of being balanced
    void balance( AvlNode * & t )
    {
        if( t == nullptr )
            return;
      
        if( height( t->left ) - height( t->right ) > ALLOWED_IMBALANCE )
            if( height( t->left->left ) >= height( t->left->right ) )
                rotateWithLeftChild( t );
            else
                doubleWithLeftChild( t );
        else
        if( height( t->right ) - height( t->left ) > ALLOWED_IMBALANCE )
            if( height( t->right->right ) >= height( t->right->left ) )
                rotateWithRightChild( t );
            else
                doubleWithRightChild( t );
              
        t->height = max( height( t->left ), height( t->right ) ) + 1;
    }
  
    /**
     * Internal method to find the smallest item in a subtree t.
     * Return node containing the smallest item.
     */
    AvlNode * findMin( AvlNode *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.
     */
    AvlNode * findMax( AvlNode *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 tree.
     */
    bool contains( const Comparable & x, AvlNode *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
    }

/****** NONRECURSIVE VERSION*************************
    bool contains( const Comparable & x, AvlNode *t ) const
    {
        while( t != nullptr )
            if( x < t->element )
                t = t->left;
            else if( t->element < x )
                t = t->right;
            else
                return true;    // Match

        return false;   // No match
    }
*****************************************************/

    /**
     * Internal method to make subtree empty.
     */
    void makeEmpty( AvlNode * & t )
    {
        if( t != nullptr )
        {
            makeEmpty( t->left );
            makeEmpty( t->right );
            delete t;
        }
        t = nullptr;
    }

    /**
     * Internal method to print a subtree rooted at t in sorted order.
     */
    void printTree( AvlNode *t ) const
    {
        if( t != nullptr )
        {
            printTree( t->left );
            cout << t->element << endl;
            printTree( t->right );
        }
    }

    /**
     * Internal method to clone subtree.
     */
    AvlNode * clone( AvlNode *t ) const
    {
        if( t == nullptr )
            return nullptr;
        else
            return new AvlNode{ t->element, clone( t->left ), clone( t->right ), t->height };
    }
        // Avl manipulations
    /**
     * Return the height of node t or -1 if nullptr.
     */
    int height( AvlNode *t ) const
    {
        return t == nullptr ? -1 : t->height;
    }

    int max( int lhs, int rhs ) const
    {
        return lhs > rhs ? lhs : rhs;
    }

    /**
     * Rotate binary tree node with left child.
     * For AVL trees, this is a single rotation for case 1.
     * Update heights, then set new root.
     */
    void rotateWithLeftChild( AvlNode * & k2 )
    {
        AvlNode *k1 = k2->left;
        k2->left = k1->right;
        k1->right = k2;
        k2->height = max( height( k2->left ), height( k2->right ) ) + 1;
        k1->height = max( height( k1->left ), k2->height ) + 1;
        k2 = k1;
    }

    /**
     * Rotate binary tree node with right child.
     * For AVL trees, this is a single rotation for case 4.
     * Update heights, then set new root.
     */
    void rotateWithRightChild( AvlNode * & k1 )
    {
        AvlNode *k2 = k1->right;
        k1->right = k2->left;
        k2->left = k1;
        k1->height = max( height( k1->left ), height( k1->right ) ) + 1;
        k2->height = max( height( k2->right ), k1->height ) + 1;
        k1 = k2;
    }

    /**
     * Double rotate binary tree node: first left child.
     * with its right child; then node k3 with new left child.
     * For AVL trees, this is a double rotation for case 2.
     * Update heights, then set new root.
     */
    void doubleWithLeftChild( AvlNode * & k3 )
    {
        rotateWithRightChild( k3->left );
        rotateWithLeftChild( k3 );
    }

    /**
     * Double rotate binary tree node: first right child.
     * with its left child; then node k1 with new right child.
     * For AVL trees, this is a double rotation for case 3.
     * Update heights, then set new root.
     */
    void doubleWithRightChild( AvlNode * & k1 )
    {
        rotateWithLeftChild( k1->right );
        rotateWithRightChild( k1 );
    }


    /*****************************************************/
    // START OF ASSIGNMENT 2

    // Print the enzyme and recognition sequence that matches
    void search( const Comparable & x, AvlNode * & t ) const
    {
        if( x < t->element )
            return search( x, t->left );
        else if( t->element < x )
            return search( x, t->right );
        else {
            t->element.printAllEnzAcroOfRecSeq();    // Match
        }
    }

    // Return number of Nodes in the tree
    int numOfNodes (AvlNode *t) const {
        if (t == nullptr) {
            return 0;
        }
        else {
            return 1 + numOfNodes(t->left) + numOfNodes(t->right);
        }
    }

    // Calculate the number of paths in tree
    float numOfPaths (AvlNode *t, float pathsTracker) const {
        if (t == nullptr) {
            return 0;
        }
        else {
            return pathsTracker + numOfPaths(t->left, pathsTracker + 1) + numOfPaths(t->right, pathsTracker + 1);
        }
    }

    // Search if the SequenceMap object is in the tree,
    // Also updates the total number of recursion calls
    bool contains( const Comparable & x, AvlNode *t, float &recursionCalls) {
        if( t == nullptr )
            return false;
        else if( x < t->element ) {
            recursionCalls++;
            return contains( x, t->left, recursionCalls);
        }
        else if( t->element < x ) {
            recursionCalls++;
            return contains( x, t->right, recursionCalls);
        }
        else
            return true;    // Match
    }
  
    // Remove the node that matches this node
    // Also updates the total number of recursion calls
    void remove( const Comparable & x, AvlNode * & t, float &recursionCalls, bool &removedNode)
    {
        if( t == nullptr ){
            return;
        }
        if( x < t->element ) {
            recursionCalls++;
            remove( x, t->left, recursionCalls, removedNode);
        }
        else if( t->element < x ) {
            recursionCalls++;
            remove( x, t->right, recursionCalls, removedNode);
        }
        else if( t->left != nullptr && t->right != nullptr ) // Two children
        {
            t->element = findMin( t->right )->element;
            recursionCalls++;
            remove( t->element, t->right, recursionCalls, removedNode);
        }
        else
        {
            removedNode = true;
            AvlNode *oldNode = t;
            t = ( t->left != nullptr ) ? t->left : t->right;
            delete oldNode;
        }
      
        balance( t );
    }

    //END OF ASSIGNMENT 2
    /*****************************************************/

};

#endif


BinarySearchTree.h

#ifndef BINARY_SEARCH_TREE_H
#define BINARY_SEARCH_TREE_H

#include "dsexceptions.h"
#include <iostream>
#include <algorithm>
using namespace std;     

// BinarySearchTree class
//
// CONSTRUCTION: zero parameter
//
// ******************PUBLIC OPERATIONS*********************
// void insert( x )       --> Insert x
// void remove( x )       --> Remove x
// bool contains( x )     --> Return true if x is present
// Comparable findMin( ) --> Return smallest item
// Comparable findMax( ) --> Return largest item
// boolean isEmpty( )     --> Return true if empty; else false
// void makeEmpty( )      --> Remove all items
// void printTree( )      --> Print tree in sorted order
// ******************ERRORS********************************
// Throws UnderflowException as warranted

template <typename Comparable>
class BinarySearchTree
{
public:
    BinarySearchTree( ) : root{ nullptr }
    {
    }

    /**
     * Copy constructor
     */
    BinarySearchTree( const BinarySearchTree & rhs ) : root{ nullptr }
    {
        root = clone( rhs.root );
    }

    /**
     * Move constructor
     */
    BinarySearchTree( BinarySearchTree && rhs ) : root{ rhs.root }
    {
        rhs.root = nullptr;
    }
  
    /**
     * Destructor for the tree
     */
    ~BinarySearchTree( )
    {
        makeEmpty( );
    }

    /**
     * Copy assignment
     */
    BinarySearchTree & operator=( const BinarySearchTree & rhs )
    {
        BinarySearchTree copy = rhs;
        std::swap( *this, copy );
        return *this;
    }
      
    /**
     * Move assignment
     */
    BinarySearchTree & operator=( BinarySearchTree && rhs )
    {
        std::swap( root, rhs.root );     
        return *this;
    }
  
  
    /**
     * Find the smallest item in the tree.
     * Throw UnderflowException if empty.
     */
    const Comparable & findMin( ) const
    {
        if( isEmpty( ) )
            throw UnderflowException{ };
        return findMin( root )->element;
    }

    /**
     * Find the largest item in the tree.
     * Throw UnderflowException if empty.
     */
    const Comparable & findMax( ) const
    {
        if( isEmpty( ) )
            throw UnderflowException{ };
        return findMax( root )->element;
    }

    /**
     * Test if the tree is logically empty.
     * Return true if empty, false otherwise.
     */
    bool isEmpty( ) const
    {
        return root == nullptr;
    }

    /**
     * Print the tree contents in sorted order.
     */
    void printTree( ostream & out = cout ) const
    {
        if( isEmpty( ) )
            out << "Empty tree" << endl;
        else
            printTree( root, out );
    }

    /**
     * Make the tree logically empty.
     */
    void makeEmpty( )
    {
        makeEmpty( root );
    }

    /**
     * Insert x into the tree; duplicates are ignored.
     */
    void insert( const Comparable & x )
    {
        insert( x, root );
    }
   
    /**
     * Insert x into the tree; duplicates are ignored.
     */
    void insert( Comparable && x )
    {
        insert( std::move( x ), root );
    }
  

    /**
     * Returns true if x is found in the tree.
     */
    bool contains( const Comparable & x) const
    {
        return contains( x, root );
    }

    /**
     * Remove x from the tree. Nothing is done if x is not found.
    void remove( const Comparable & x )
    {
        remove( x, root );
    }
    */

    /*****************************************************/
    // START OF ASSIGNMENT 2:

    void search( const Comparable & x ) {
        search(x, root);
    }
    int numOfNodes() {
        return numOfNodes(root);
    }
    float numOfPaths() {
        float pathTracker = 0.00;
        return numOfPaths(root, pathTracker);
    }
    bool contains(const Comparable & x, float &recursionCalls) {
        return contains(x, root, recursionCalls);
    }
    void remove(const Comparable & x, float &recursionCalls, bool &removedNode) {
        remove(x, root, recursionCalls, removedNode);
    }

    //END OF ASSIGNMENT 2
    /*****************************************************/


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

        BinaryNode( const Comparable & theElement, BinaryNode *lt, BinaryNode *rt )
          : element{ theElement }, left{ lt }, right{ rt } { }
      
        BinaryNode( Comparable && theElement, BinaryNode *lt, BinaryNode *rt )
          : element{ std::move( 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 Comparable & 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 {
            t->element.Merge(x);
        }
    }
  
    /**
     * 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( Comparable && x, BinaryNode * & t )
    {
        if( t == nullptr )
            t = new BinaryNode{ std::move( x ), nullptr, nullptr };
        else if( x < t->element )
            insert( std::move( x ), t->left );
        else if( t->element < x )
            insert( std::move( x ), t->right );
        else
            t->element.Merge(x);
    }

    /**
     * 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 Comparable & 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
    }

/****** NONRECURSIVE VERSION*************************
    bool contains( const Comparable & x, BinaryNode *t ) const
    {
        while( t != nullptr )
            if( x < t->element )
                t = t->left;
            else if( t->element < x )
                t = t->right;
            else
                return true;    // Match

        return false;   // No match
    }
*****************************************************/

    /**
     * Internal method to make subtree empty.
     */
    void makeEmpty( BinaryNode * & t )
    {
        if( t != nullptr )
        {
            makeEmpty( t->left );
            makeEmpty( t->right );
            delete t;
        }
        t = nullptr;
    }

    /**
     * Internal method to print a subtree rooted at t in sorted order.
     */
    void printTree( BinaryNode *t, ostream & out ) const
    {
        if( t != nullptr )
        {
            printTree( t->left, out );
            out << t->element << endl;
            printTree( t->right, out );;
        }
    }

    /**
     * Internal method to clone subtree.
     */
    BinaryNode * clone( BinaryNode *t ) const
    {
        if( t == nullptr )
            return nullptr;
        else
            return new BinaryNode{ t->element, clone( t->left ), clone( t->right ) };
    }


    /*****************************************************/
    // START OF ASSIGNMENT 2

    // Print the enzyme and recognition sequence that matches
    void search( const Comparable & x, BinaryNode *t ) const
    {
        if( t == nullptr )
            return;
        else if( x < t->element )
            return search( x, t->left );
        else if( t->element < x )
            return search( x, t->right );
        else {
            t->element.printAllEnzAcroOfRecSeq();    // Match
        }
    }
  
    // Return number of Nodes in the tree
    int numOfNodes (BinaryNode *t) const {
        if (t == nullptr) {
            return 0;
        }
        else {
            return numOfNodes(t->left) + numOfNodes(t->right) + 1;
        }
    }

    // Calculate the number of Paths in the tree
    float numOfPaths (BinaryNode *t, float pathsTracker) const {
        if (t == nullptr) {
            return 0;
        }
        else {
            return numOfPaths(t->left, pathsTracker + 1) + numOfPaths(t->right, pathsTracker + 1) + pathsTracker;
        }
    }

    // Search if the SequenceMap object is in the tree,
    // Also updates the total number of recursion calls
    bool contains( const Comparable & x, BinaryNode *t, float &recursionCalls) {
        if( t == nullptr )
            return false;
        else if( x < t->element ) {
            recursionCalls++;
            return contains( x, t->left, recursionCalls);
        }
        else if( t->element < x ) {
            recursionCalls++;
            return contains( x, t->right, recursionCalls);
        }
        else
            return true;    // Match
    }

    // Remove the node that matches this node
    // Also updates the total number of recursion calls
    void remove( const Comparable & x, BinaryNode * & t, float &recursionCalls, bool &removedNode)
    {
        if( t == nullptr )
            return;
        if( x < t->element ){
            recursionCalls++;
            remove( x, t->left, recursionCalls, removedNode );
        }
        else if( t->element < x ) {
            recursionCalls++;
            remove( x, t->right, recursionCalls, removedNode );
        }
        else if( t->left != nullptr && t->right != nullptr ) { // Two children
            recursionCalls++;
            t->element = findMin( t->right )->element;
            remove( t->element, t->right, recursionCalls, removedNode );
        }
        else
        {
            removedNode = true;
            BinaryNode *oldNode = t;
            t = ( t->left != nullptr ) ? t->left : t->right;
            delete oldNode;
        }
    }


    //END OF ASSIGNMENT 2
    /*****************************************************/


};

#endif

SequenceMap.cpp

#include "SequenceMap.h"

int main() {
   string recSequence = "SEQUENCE";
   string recSequence_ = "SEQUENCE_";
   string enzymeOne = "enzymeOne";
   string thingS = "THINGS";
   string enzymeThree = "enzymeThree";
   SequenceMap mySM(recSequence, enzymeOne);
   SequenceMap anotherSM(recSequence, enzymeThree);
   SequenceMap diffSM(thingS, thingS);
   if (mySM < diffSM) {
       cout << "it is true" << endl;
   }
   else {
       cout << "it is false" << endl;
   }
   //cout << mySM;
   mySM.Merge(diffSM);
   mySM.Merge(anotherSM);

   cout << "###############" << endl;
   cout << mySM;
   //*/
   return 0;
}

SequenceMap.h

#ifndef SEQUENCEMAP_H
#define SEQUENCEMAP_H

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class SequenceMap {
public:
   // Zero-parameter constructor.
    SequenceMap() = default;
    // Copy-constructor.
    SequenceMap(const SequenceMap &rhs) = default;
    // Copy-assignment.
    SequenceMap& operator=(const SequenceMap &rhs) = default;
    // Move-constructor.
   SequenceMap(SequenceMap &&rhs) = default;
   // Move-assignment.
   SequenceMap& operator=(SequenceMap &&rhs) = default;
   // Destructor.
   ~SequenceMap() = default;

   // Start of Part 1

   // Constructor for recognition sequence and enzyme acronym
   SequenceMap(const string &a_rec_seq, const string &an_enz_acro) {
       recognition_sequence_ = a_rec_seq;
       enzyme_acronyms_.push_back(an_enz_acro);
   }

   // Constructor for recognition sequence only
   SequenceMap(const string &a_rec_seq) {
       recognition_sequence_ = a_rec_seq;
       enzyme_acronyms_.push_back("");
   }

   // Overload the < operator
   bool operator<(const SequenceMap &rhs) const {
       return (recognition_sequence_ < rhs.recognition_sequence_);
   }

   // Overload the << operator to print the recognition sequence with enzyme acronyms
   friend std::ostream &operator<<(std::ostream &out, const SequenceMap &a_SequenceMap) {
       out << a_SequenceMap.recognition_sequence_ << "   ";
       for (int i = 0; i < a_SequenceMap.enzyme_acronyms_.size(); ++i) {
           out << a_SequenceMap.enzyme_acronyms_[i] << " ";
       }
       return out;
   }

   // Merge two SequenceMap objects
   void Merge(const SequenceMap &other_sequence) {
       for (int i = 0; i < other_sequence.enzyme_acronyms_.size(); ++i) {
           enzyme_acronyms_.push_back(other_sequence.enzyme_acronyms_[i]);  
       }
   }

   // Print the recognition sequence
   string getRecognitionSequence() const {
       return recognition_sequence_;
   }

   // Print enzyme acronym
   void printAllEnzAcroOfRecSeq() const {
       for (int i = 0; i < enzyme_acronyms_.size() ; ++i) {
           cout << enzyme_acronyms_[i] << "   ";  
       }
       cout << endl;
   }


private:
   string recognition_sequence_ ;
   vector<string> enzyme_acronyms_;
};

#endif

query_tree.cc

// Main file for Part2(a) of Homework 2.

#include "AvlTree.h"
#include "BinarySearchTree.h"
#include "SequenceMap.h"

#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;

namespace {

// @db_filename: an input filename.
// @a_tree: an input tree of the type TreeType. It is assumed to be
// empty.
template <typename TreeType>
void QueryTree(const string &db_filename, TreeType &a_tree) {
// Code for running Part2(a)

// Open file
ifstream fin;
fin.open(db_filename);
if (!fin) { //test if file is openable
    cout << "Unable to open file" << endl;
}

string db_line;

if (db_filename == "rebase210.txt") {
    //rid the header of the file
    for (int i = 0; i < 10; ++i) {
      getline(fin, db_line);
    }

    // Start to set and store the sequence itself
    while(getline(fin, db_line)) {
      if (db_line.empty()) {
        break;
      }

      stringstream ss(db_line);
      string enzAcro;
      getline(ss, enzAcro, '/'); // Store enzyme only

      string recSeq;
      while(getline(ss, recSeq, '/')) { // Store recognition sequence
        if (recSeq != "") { // If the recognition sequence is NOT empty
          SequenceMap tempSequenceMap(recSeq, enzAcro);
          a_tree.insert(tempSequenceMap);
        }    
      }
    }
}

if (db_filename == "sequences.txt") { //file contains only sequences
    // Start to set and store the sequence itself
    while(getline(fin, db_line)) {
      SequenceMap tempSequenceMap(db_line);
      a_tree.insert(tempSequenceMap);
    }
}

fin.close();


// Take in sequences from user
string userSequence;
cout << "Please enter 'EXIT' to exit" << endl;
while (getline(cin, userSequence)) {
    if (userSequence != "EXIT") {
      if (!a_tree.contains(userSequence)) {
        cout << "Not Found" << endl;
      }
      else { // Find sequence and print out the enzyme acronym
        a_tree.search(userSequence);
      }  
    }
    else if (userSequence == "EXIT") {
      break;
    }
}

// You can use public functions of TreeType. For example:
//a_tree.insert(10);
//a_tree.printTree();

} // QueryTree

} // namespace

int
main(int argc, char **argv) {
if (argc != 3) {
    cout << "Usage: " << argv[0] << " <databasefilename> <tree-type>" << endl;
    return 0;
}
const string db_filename(argv[1]);
const string param_tree(argv[2]);
cout << "Input filename is " << db_filename << endl;
cout << "Type of tree is " << param_tree << endl;
if (param_tree == "BST") {
    // Note that you will replace BinarySearchTree<int> with BinarySearchTree<SequenceMap>
    BinarySearchTree<SequenceMap> a_tree;
    QueryTree(db_filename, a_tree);
}
else if (param_tree == "AVL") {
    // Note that you will replace AvlTree<int> with AvlTree<SequenceMap>
    AvlTree<SequenceMap> a_tree;
    QueryTree(db_filename, a_tree);
}
else {
    cout << "Uknown tree type " << param_tree << " (User should provide BST, or AVL)" << endl;
}
return 0;
}

Add a comment
Know the answer?
Add Answer to:
After the header, each line of the database file rebase210.txt contains the name of a restriction...
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
  • In C++ I need the printRange function, and the main.cpp program. Thanks. (Binary search tree) Write...

    In C++ I need the printRange function, and the main.cpp program. Thanks. (Binary search tree) Write a function printRange that takes as input a binary search tree t and two keys, k1 and k2, which are ordered so that k1 < k2, and print all elements x in the tree such that k1 <= x <= k2. You can add this function in BinarySearchTree.h (click the link) that we used in the lecture and lab 7. public: void printRange(int k1,...

  • Take the following code for a binary source tree and make it include the following operations....

    Take the following code for a binary source tree and make it include the following operations. bool replace(const Comparable & item, const Comparable & replacementItem); int getNumberOfNodes() const; (a) The replace method searches for the node that contains item in a binary search tree, if it is found, it replaces item with replacementItem. The binary tree should remain as a binary search tree after the replacement is done. Add the replace operation to the BinarySearchTree class. Test your replace using...

  • please write the code in C++ Implement the BinarySearchTree ADT in a file BinarySearchTree.h exactly as...

    please write the code in C++ 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 <cassert> #include <iostream> using namespace std; template <typename C> class BinarySearchTree { public: BinarySearchTree( ) : root{ nullptr } { } ~BinarySearchTree( ) { makeEmpty(); } const C & findMin( ) const { assert(!isEmpty()); return findMin( root )->element; } const C & findMax( ) const...

  • In C++ and use functions that are asked for, thanks! Implement the BinarySearchTree ADT in a...

    In C++ and use functions that are asked for, thanks! 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 <cassert> #include <iostream> using namespace std; template <typename C> class BinarySearchTree { public: BinarySearchTree( ) : root{ nullptr } { } ~BinarySearchTree( ) { makeEmpty(); } const C & findMin( ) const { assert(!isEmpty()); return findMin( root )->element; } const C...

  • C++: PLEASE HELP~!!! ~~~~~~~~ Implement bool AVLTree::deleteNode(string ss) method. Function deleteNode() tries to delete the node...

    C++: PLEASE HELP~!!! ~~~~~~~~ Implement bool AVLTree::deleteNode(string ss) method. Function deleteNode() tries to delete the node containing value ss. If there is no such node, it returns false. Otherwise, it deletes the node, check the balance of the tree, rebalance the tree if it is necessary. When you delete a node, consider three different scenarios: -The node is a leaf -The node has only ONE child subtree -The node has two child subtrees Important: When you implement this project, do...

  • C++, implement the bst.cpp file without adding any additional methods or functions to it ======================================================================== //...

    C++, implement the bst.cpp file without adding any additional methods or functions to it ======================================================================== // bst.cpp #include <iostream> #include "bst.h" using namespace std; BinarySearchTree::BinarySearchTree() { root = nullptr; } void BinarySearchTree::insert(int key, string val) { Node* new_node = new Node; new_node->key = key; new_node->val = val; new_node->left = nullptr; new_node->right = nullptr; if (root == nullptr) { root = new_node; } else { insertHelper(root, new_node); } } void BinarySearchTree::insertHelper(Node* parent, Node* new_node) { if (new_node->key < parent->key) { if...

  • Write a function, swapSubtrees, that swaps all of the left and right subtrees of a binary...

    Write a function, swapSubtrees, that swaps all of the left and right subtrees of a binary tree. Add this function to the class binaryTreeType and create a program to test this function. #include <iostream> using namespace std; //Definition of the Node template <class elemType> struct nodeType { elemType info; nodeType<elemType> *lLink; nodeType<elemType> *rLink; }; //Definition of the class template <class elemType> class binaryTreeType { public: //Overload the assignment operator. const binaryTreeType<elemType>& operator=(const binaryTreeType<elemType>&) { if (this != &otherTree) //avoid self-copy...

  • BST.cpp #include "BST.h" #include "BT-visualize.h" #include <assert.h> #include <stdio....

    BST.cpp #include "BST.h" #include "BT-visualize.h" #include <assert.h> #include <stdio.h> #include <string.h> #include <string> // Implement the following five methods // inserts val into BST rooted at x and returns the tree's new root BTnode * insert(BTnode * x, int val) {} // returns true iff target in tree rooted at x bool search(BTnode * x, int target) {} // Find the maximum value of a tree rooted at x int findmax(BTnode * x) {} // Find the manimum value of...

  • Write a method that determines the key of the successor of the root node in a...

    Write a method that determines the key of the successor of the root node in a binary search tree. For any input binary search tree, find the key of successor of the root node.Note: Successor is the node with the next highest key,  should work for any binary search tree - not just the given example input. #include <iostream> using namespace std; class Node { private: int key; string val; Node* left; Node* right; friend class BinarySearchTree; }; class BinarySearchTree {...

  • Hi there, I am working on a binary search tree code in c++. The program must...

    Hi there, I am working on a binary search tree code in c++. The program must store and update students' academic records, each node includes the student name, credits attempted, credits earned and GPA. I have made some progress with the code and written most of the functions in the .cpp file (already did the .h file) but i am struggling with what to put in the main and how to put an update part in the insert function. I...

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