Question

In: Computer Science

For this computer assignment, you are to write a C++ program to implement a class for...

For this computer assignment, you are to write a C++ program to implement a class for binary trees. To deal with variety of data types, implement this class as a template.

Most of the public member functions of the BinaryTree class call private member functions of the class (with the same name). These private member functions can be implemented as either recursive or non-recursive, but clearly, recursive versions of these functions are preferable because of their short and simple implementations in code. However, they require more memory and usually slower than their non-recursive versions in execution, especially for a large amount of input data.

BINARYTREE.H

#include

#include "node.h"

using namespace std;

#ifndef H_BINARYTREE

#define H_BINARYTREE

template class BinaryTree{

public:

    BinaryTree();                                      // default constructor

    unsigned     getSize() const;                      // returns size of tree

    unsigned     getHeight() const;                    // returns height of tree

    virtual void Insert(const T&);                     // inserts node in tree

    void         Inorder(void (*)(const T&));          // inorder traversal of tree

protected:

    Node *root;                                      // root of tree

private:

    unsigned _getSize(Node *) const;                 // private version of getSize()

    unsigned _getHeight(Node *) const;               // private version of getHeight()

    void     _Insert(Node *&, const T&);             // private version of Insert()

    void     _Inorder(Node *, void (*)(const T&));   // private version of Inorder()

};

#endif // End of H_BINARYTREE

Because of information hiding, a client is not permitted to access the binary tree directly, so the root of the tree is kept protected (not private because of future implementations of derived classes from the base class of the BinaryTree), so it cannot be passed as an argument to any of the public functions of the tree. It is essential to have private utility functions, which act as interface between a client and the tree. The Insert() function of the BinaryTree class is described as follows:

  • Insert(const T &x) This virtual function can be used to insert a node with the data value x in a binary tree, applying the following technique: if the tree is empty, then the new node will be the root of the tree with the value x; otherwise, the left or the right subtree is randomly selected and the value x is inserted in that side. To implement the random selection, you can use the following RNG.
typedef enum {left_side, right_side } SIDE;

SIDE rnd(){ 
    return rand()%2 ? right_side : left_side;
}// End of rnd()

Put the implementation of your BinaryTree class in the header file binarytree.h. Definition of the class Node, which represents the nodes in a binary tree, can be found in the header file node.h. To use the class Node in your program, include the header file node.h, inserting #include "node.h" at the top of your header file.

The source file binarytreeDriver.cc contains the driver program. In addition to the main() routine, it has the implementations of the following routines (as templates) and the definitions of the two RNGs used in the main() routine.

  • template void print(const T &x):
  • template void printValues(BinaryTree &tree, const string &name);

The unary function print() can be used as an argument to the member functions Inorder() to print the value of its argument x. The function printValues() does the followings:

  • it prints name, which is the name of the tree, and it also prints the height of the tree.
  • it calls the member function Inorder() to print the data values in the tree in inorder.

The class RND1 can be used to generate random integers in the range [LOW1 = –999, HIGH1 = 999] and the class RND2 can be used to generate random floating-point numbers in the range [LOW2 = –999.99, HIGH2 = 999.99]. The function objects RND1() and RND2(), generated from these classes, are used to fill in the random values in vector containers vector A(N1) and vector B(N2) by using the generate() function in the STL, where N1 = 100 and N2 = 50 are the sizes of these two vectors.

The main() routine copies the random values from vectors A and B and inserts them in the binary trees first and second, respectively. At the end, the data values in the binary trees first and second are printed out on stdout with LSIZE = 12 numbers in a single line.

Put the implementation of your BinaryTree class in the header file binarytree.h. Definition of the class Node, which represents the nodes in a binary tree, can be found in the header file node.h. To use the class Node in your program, include the header file node.h, inserting #include "node.h" at the top of your header file.

The source file binarytreeDriver.cc contains the driver program. In addition to the main() routine, it has the implementations of the following routines (as templates) and the definitions of the two RNGs used in the main() routine.

  • template void print(const T &x):
  • template void printValues(BinaryTree &tree, const string &name);

The unary function print() can be used as an argument to the member functions Inorder() to print the value of its argument x. The function printValues() does the followings:

  • it prints name, which is the name of the tree, and it also prints the height of the tree.
  • it calls the member function Inorder() to print the data values in the tree in inorder.

The class RND1 can be used to generate random integers in the range [LOW1 = –999, HIGH1 = 999] and the class RND2 can be used to generate random floating-point numbers in the range [LOW2 = –999.99, HIGH2 = 999.99]. The function objects RND1() and RND2(), generated from these classes, are used to fill in the random values in vector containers vector A(N1) and vector B(N2) by using the generate() function in the STL, where N1 = 100 and N2 = 50 are the sizes of these two vectors.

The main() routine copies the random values from vectors A and B and inserts them in the binary trees first and second, respectively. At the end, the data values in the binary trees first and second are printed out on stdout with LSIZE = 12 numbers in a single line.

BINARYTREE.CC

#include

#include

#include

#include

#include

using namespace std;

#include "binarytree.h"

#define SEED 1  // seed for RNGs

#define N1    100   // size of 1st vector container

#define LOW1  -999  // low val for rand integer

#define HIGH1 999   // high val for rand integer

#define N2    50      // size of 2nd vector container

#define LOW2  -99999  // low val for rand float

#define HIGH2 99999   // high val for rand float

#define PREC  2       // no of digits after dec pt

#define LSIZE  12  // no of vals printed on line

#define ITEM_W 7   // no of spaces for each item

// prints single val

template

void print(const T&);

// prints data vals in tree

template

void print_vals(BinaryTree&, const string&);

// class to generate rand ints

class RND1 {

private:

  int low, high;

public:

  RND1(const int& l = 0, const int& h = 1) : low(l), high(h) {}

  int operator()() const { return rand() % (high - low + 1) + low; }

};

// class to generate rand floats

class RND2 {

private:

  int low, high, prec;

public:

  RND2(const int& l = 0, const int& h = 1, const int& p = 0) : low(l), high(h), prec(p) {}

  float operator()() const { return (static_cast(rand() % (high - low + 1) + low)) / pow(10, prec); }

};

// prints val passed as argument

template

void print(const T& x) {

  static unsigned cnt = 0;

  cout << setw(ITEM_W) << x << ' ';

  cnt++;

  if (cnt % LSIZE == 0) cout << endl;

}

// prints size and height of bin tree and data val in

// each node in inorder

template

void print_vals(BinaryTree& tree, const string& name) {

  cout << name << ": ";  // print name of tree

  // print size and height of tree

  cout << "size = " << tree.getSize() << ", ";

  cout << "height = " << tree.getHeight() << endl << endl;

  // print data values of tree in inorder

  cout << "Data values in '" << name << "' inorder:\n\n";

  tree.Inorder(print);

  cout << endl;

}

// driver program: to test several member functions of BinaryTree class

int main() {

  srand(SEED);  // set seed for RNGs

  // create 1st vector and fill it with rand ints

  vector A(N1);

  generate(A.begin(), A.end(), RND1(LOW1, HIGH1));

  // create binary tree with int vals in vector A,

  // and print all vals of tree

  BinaryTree first;

  for (unsigned i = 0; i < A.size(); i++) first.Insert(A[i]);

  print_vals(first, "first");

  cout << endl;

  // create 2nd vector and fill it with rand floats

  vector B(N2);

  generate(B.begin(), B.end(), RND2(LOW2, HIGH2, PREC));

  // create binary tree with float vals in vector B,

  // and print all vals of tree

  BinaryTree second;

  for (unsigned i = 0; i < B.size(); i++) second.Insert(B[i]);

  print_vals(second, "second");

  cout << endl;

  return 0;

}

NODE.H

#ifndef H_NODE

#define H_NODE

// definition of node in bin tree

template

class BinaryTree;  // forward declaration

template

class Node {

  friend class BinaryTree;  // BinaryTree is friend

public:

  Node(const T& = T(), Node* = nullptr, Node* = nullptr);  // default constructor

private:

  T        data;   // data component

  Node* left;   // left pointer

  Node* right;  // right pointer

};

// default constructor

template

Node::Node(const T& x, Node* l, Node* r) : data(x), left(l), right(r) {}

#endif  // End of H_NODE

Solutions

Expert Solution

The code is

Node.h

#ifndef NODE_H
#define NODE_H

template <class T> class binTree;

template <class T> class Node
{
   friend class binTree <T>;
   public:
       //The node defualt constructor
       Node ( const T& =T ( ), Node <T>* = 0, Node <T>* = 0 );

   private:
       T nodeContent;
       Node <T> *leftChild, *childRight;
};

// default constructor
template <class T>
Node <T>:: Node( const T& temp, Node <T>* newLeft, Node <T>* newRight )
{
   nodeContent = temp;
   leftChild = newLeft;
   childRight = newRight;
}

#endif

binTree.h

#ifndef BINTREE_H
#define BINTREE_H

#include "Node.h"

template <class T> class binTree
{
   public:

       binTree ( );
       int height ( ) const;
       virtual void insert ( const T& );
       void inOrder ( void ( * ) ( T& ));
   protected:
       Node <T>* root;
   private:
       int height ( Node <T>* ) const;
       void insert ( Node <T>*&, const T& );
       void inOrder ( Node <T>*, void ( * ) ( T& ));
};

//function definitions
template <class T>
binTree <T>::binTree( )
{
   //set the root
   root = 0;
}


// returns height of tree
template <class T>
int binTree <T>::height( ) const
{
    return height( root ); // call recursive
}

//to insert the node in the binary tree
//recursive function
template <class T>
void binTree <T>::insert( const T& temp )
{
    insert( root, temp );
}

//To perform inorder traversal of the tree
template <class T>
void binTree <T>::inOrder( void ( *print ) ( T& ) )
{
    inOrder( root, print );
}

// private version of height
template <class T>
int binTree <T>::height( Node <T>* ptr ) const
{
   if( ptr == 0 )
   {
       return 0;
   }
   else
   {
       int heightleft = height( ptr->leftChild );
       int heigRight = height( ptr->childRight );
  
       if( heightleft > heigRight )
       {
           return 1 + heightleft;
       }
       else
       {
           return 1 + heigRight;
       }
   }
}

template <class T>
void binTree <T>::insert( Node <T>* & nod, const T& temp )
{
   if( nod == 0 )
   {
       Node <T> * newNode;
       newNode = new Node <T>( temp );
       nod = newNode;
   }     
   else
   {
       int heightleft = height( nod->leftChild );
       int heigRight = height( nod->childRight );
  
       if( heightleft <= heigRight )
       {
           insert( nod->leftChild, temp );
       }
       else
       {
           insert( nod->childRight, temp );
       }
   }
}

//inorder traversa
template <class T>
void binTree <T>::inOrder( Node <T>* nod, void ( *print ) ( T& ) )
{
   if( nod != NULL )
   {
       inOrder( nod->leftChild, print );
       print( nod->nodeContent );
       inOrder( nod->childRight, print );
   }
}

#endif

prog6.cpp

#include <iostream>
#include<cstdlib>
#include <ctime>
#include <vector>
#include <algorithm>
#include "binTree.h"

using namespace std;
class RND1{
   int x;
public:
   static int RND(){
   srand(time(NULL));
   return (-999+ (rand() % (static_cast<int>(999 +999 + 1))));
   srand(time(NULL));
   }

};


class RND2{
   float randm;
public:
   static float RND()
   {
       srand(time(NULL));
       return -999.99 + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(999.99+999.99)));
   }

};

template <class T>
void print(T a)
{
    cout<<a<<" ";
}

int main()
{
    srand(unsigned(time(0)));
    vector<int> A(100);
    vector<float> B(50);
    RND1 obj3=RND1();

    std::cout << "\nIn order traversal of int tree: \n";
    binTree <int> tr=binTree <int> ( );
    int count=1;
    generate(A.begin(), A.end(), &RND1::RND);
    for (auto iv: A) {
           tr.insert(iv);
    }

tr.inOrder(&print);

    //float tree
        std::cout << "\n\nIn order traversal of float tree: \n";
   binTree <float> tr1=binTree <float> ( );
   generate(B.begin(), B.end(), &RND2::RND);
   for (auto iv: B) {
            tr1.insert(iv);
          }

   tr1.inOrder(&print);
   //print heights

   cout<<"\nint tree height"<<tr.height();

   cout<<"\nfloat tree height"<<tr1.height();
   cout<<endl;
    system("pause");
    return 0;
}

Hope this is helpful

Pleaase please dont downvote


Related Solutions

For this computer assignment, you are to write a C++ program to implement a class for...
For this computer assignment, you are to write a C++ program to implement a class for binary trees. To deal with variety of data types, implement this class as a template. Most of the public member functions of the BinaryTree class call private member functions of the class (with the same name). These private member functions can be implemented as either recursive or non-recursive, but clearly, recursive versions of these functions are preferable because of their short and simple implementations...
For this computer assignment, you are to write and implement an interactive C++ program to find...
For this computer assignment, you are to write and implement an interactive C++ program to find and print all prime numbers, which are less than or equal to a given value of n, using the algorithm known as the Sieve of Eratosthenes. A prime number p is an integer greater than 1 that is divisible only by 1 and p (itself). The algorithm begins by initializing a set container to contain all the integers in the range 2 to n....
Write and test a C program to implement Bubble Sort. . In your C program, you...
Write and test a C program to implement Bubble Sort. . In your C program, you should do: Implement the array use an integer pointer, get the size of the array from standard input and use the malloc function to allocate the required memory for it. Read the array elements from standard input. Print out the sorted array, and don’t forget to free the memory. Debug your program using Eclipse C/C++ CDT.
using C program Assignment Write a computer program that converts a time provided in hours, minutes,...
using C program Assignment Write a computer program that converts a time provided in hours, minutes, and seconds to seconds Functional requirements Input MUST be specified in hours, minutes, and seconds MUST produce the same output as listed below in the sample run MUST correctly compute times Nonfunctional requirements MUST adhere to program template include below MUST compile without warnings and errors MUST follow the code template provided in this assignment MUST NOT change " int main() " function MUST...
For this week’s assignment, you will write a program class that has two subroutines and a...
For this week’s assignment, you will write a program class that has two subroutines and a main routine. The program should be a part of the ‘Firstsubroutines’ class and you should name your project Firstsubroutines if you are using Netbeans. Your program must prompt the user to enter a string. The program must then test the string entered by the user to determine whether it is a palindrome. A palindrome is a string that reads the same backwards and forwards,...
Program this in C thank you PROBLEM DESCRIPTION: Write a program to implement the following requirement:...
Program this in C thank you PROBLEM DESCRIPTION: Write a program to implement the following requirement: The program will read from standard input two things - a string str1 on the first line of stdin (this string may be an empty string) - a string str2 on the second line of stdin (this string may be an empty string) Note that stdin does not end with '\n'. The program will output a string that is the concatenation of string str1...
C++ Assignment 1) Write a C++ program specified below: a) Include a class called Movie. Include...
C++ Assignment 1) Write a C++ program specified below: a) Include a class called Movie. Include the following attributes with appropriate types: i. Title ii. Director iii. Release Year iv. Rating (“G”, “PG”, “PG-13”, etc) - Write code that instantiates a movie object using value semantics as text: - Write code that instantiates a movie object using reference semantics: - Write the print_movie method code: - Write Constructor code: - Write Entire Movie class declaration
In C++ For this assignment, you will write a program to count the number of times...
In C++ For this assignment, you will write a program to count the number of times the words in an input text file occur. The WordCount Structure Define a C++ struct called WordCount that contains the following data members: An array of 31 characters named word An integer named count Functions Write the following functions: int main(int argc, char* argv[]) This function should declare an array of 200 WordCount objects and an integer numWords to track the number of array...
For this week’s lab assignment, you will write a program called lab9.c. You will write a...
For this week’s lab assignment, you will write a program called lab9.c. You will write a program so that it contains two functions, one for each conversion. The program will work the same way and will produce the same exact output. The two prototypes should be the following: int btod(int size, char inputBin[size]); int dtob(int inputDec); The algorithm for the main() function should be the following: 1. Declare needed variables 2. Prompt user to enter a binary number 3. Use...
C PROGRAMMING – Steganography In this assignment, you will write an C program that includes processing...
C PROGRAMMING – Steganography In this assignment, you will write an C program that includes processing input, using control structures, and bitwise operations. The input for your program will be a text file containing a large amount of English. Your program must extract the “secret message” from the input file. The message is hidden inside the file using the following scheme. The message is hidden in binary notation, as a sequence of 0’s and 1’s. Each block of 8-bits is...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT