C++ Program 8 & More

profiletheman04
week_12_in_class_assignemnts_c.zip

Week 12 In Class Assignemnts C++/binTreeType.h

// Specification file for the BinTreeType class // PRECONDITION for use of this class: // Data type defining tree node "info" must have operators // '<', 'cout', and ==', or they must be overloaded #ifndef BINARYTREE_H #define BINARYTREE_H #include <iostream> using namespace std; template <class ItemType> class BinTreeType { private: struct TreeNode { ItemType info; TreeNode *left; TreeNode *right; }; TreeNode *root; // Overloaded functions for recursive actions void insert(TreeNode *&, TreeNode *&); void deleteIt(ItemType, TreeNode *&); void makeDeletion(TreeNode *&); void destroySubTree(TreeNode *); void getSucccessor( TreeNode* aNode, ItemType& data); void copyTree(TreeNode*& copy, const TreeNode* origTree); // Overloaded traversal functions for recursive actions void displayInOrder(TreeNode *); void displayPreOrder(TreeNode *); void displayPostOrder(TreeNode *); // Recursive functions for various utility operations int countNodes(TreeNode* tree); int getDepth(TreeNode* tree); public: BinTreeType(); // Constructor BinTreeType(BinTreeType& origTree); // Copy constructor void operator= (BinTreeType& origTree); // Overloaded assignment operator ~BinTreeType(); // Destructor // Tree data insertion, deletion, and searching void insertNode(ItemType); bool searchNode(ItemType); void deleteNode(ItemType); // Tree traversal void displayInOrder(); void displayPreOrder(); void displayPostOrder(); // Utilities for tree operations int numberOfNodes(); // Count nodes in tree int treeDepth(); }; //************************************************************* //************************************************************* // Implementation file for the BinTreeType class //************************************************************* //************************************************************* // Constructor template <class ItemType> BinTreeType<ItemType>::BinTreeType() { root = NULL; } //************************************************************* // Copy constructor - Utilizes recursive utility function // copyTree to actually replicate original tree //************************************************************* template <class ItemType> BinTreeType<ItemType>::BinTreeType(BinTreeType<ItemType>& origTree) { copyTree(root, origTree.root); } //************************************************************* // Overloaded assignment operator - Utilizes recursive utility function // copyTree to actually replicate original tree //************************************************************* template <class ItemType> void BinTreeType<ItemType>::operator= (BinTreeType<ItemType>& origTree) { destroySubTree(root); // Eliminate any existing nodes in target copyTree(root, origTree.root); // Copy source to target as part of assignment } //************************************************************* // Destructor //************************************************************* template <class ItemType> BinTreeType<ItemType>::~BinTreeType() { destroySubTree(root); } //************************************************************* // insert accepts a TreeNode pointer and a pointer to a node. * // The function inserts the node into the tree pointed to by * // the TreeNode pointer. This function is called recursively. * //************************************************************* template <class ItemType> void BinTreeType<ItemType>::insert(TreeNode *&nodePtr, TreeNode *&newNode) { if (nodePtr == NULL) nodePtr = newNode; // Insert the node. else if (newNode->info < nodePtr->info) insert(nodePtr->left, newNode); // Search the left branch else insert(nodePtr->right, newNode); // Search the right branch } //********************************************************** // insertNode creates a new node to hold num as its value, * // and passes it to the insert function. * //********************************************************** template <class ItemType> void BinTreeType<ItemType>::insertNode(ItemType num) { TreeNode *newNode; // Pointer to a new node. // Create a new node and store num in it. newNode = new TreeNode; newNode->info = num; newNode->left = newNode->right = NULL; // Insert the node. insert(root, newNode); } //*************************************************** // destroySubTree is called by the destructor. It * // deletes all nodes in the tree. * //*************************************************** template <class ItemType> void BinTreeType<ItemType>::destroySubTree(TreeNode *nodePtr) { if (nodePtr != NULL) { if (nodePtr->left != NULL) destroySubTree(nodePtr->left); if (nodePtr->right != NULL) destroySubTree(nodePtr->right); delete nodePtr; } } //*************************************************** // searchNode determines if a value is present in * // the tree. If so, the function returns true. * // Otherwise, it returns false. * //*************************************************** template <class ItemType> bool BinTreeType<ItemType>::searchNode(ItemType item) { TreeNode *nodePtr = root; while (nodePtr != NULL) { if (nodePtr->info == item) return true; else if (item < nodePtr->info) nodePtr = nodePtr->left; else nodePtr = nodePtr->right; } return false; } //********************************************** // Function deleteNode triggers the chain of * // recursive calls to search for and delete * // target node. * //********************************************** template <class ItemType> void BinTreeType<ItemType>::deleteNode(ItemType item) { deleteIt(item, root); } //*********************************************** // Function deleteIt recursively searches for * // the item to delete and calls function * // makeDeletion to perform the actual deletion. * //*********************************************** template <class ItemType> void BinTreeType<ItemType>::deleteIt(ItemType item, TreeNode *&nodePtr) { if (item < nodePtr->info) deleteIt(item, nodePtr->left); else if (item > nodePtr->info) deleteIt(item, nodePtr->right); else makeDeletion(nodePtr); } //*********************************************************** // makeDeletion takes a reference to a pointer to the node * // that is to be deleted. The node is removed and the * // branches of the tree below the node are reattached. * //*********************************************************** template <class ItemType> void BinTreeType<ItemType>::makeDeletion(TreeNode *&nodePtr) { TreeNode *tempNodePtr; // Temporary pointer, used for deletion ItemType data; if (nodePtr->right == NULL) // If no right child exists { tempNodePtr = nodePtr; nodePtr = nodePtr->left; // Then reattach the left child delete tempNodePtr; } else if (nodePtr->left == NULL) // If no left child exists { tempNodePtr = nodePtr; nodePtr = nodePtr->right; // Then reattach the right child delete tempNodePtr; } else // If the node has two children { // Get data for immediate successor (largest node in right subtree) getSucccessor(nodePtr,data); // Move information from successor node to target node nodePtr->info = data; deleteIt(data, nodePtr->right); // And delete successor node } } //**************************************************************** // This function scans for the succeeding node in order within * // a binary tree. It moves the the right child, and then moves * // down the chain of left children until NULL is reached. It * // returns the data at the predecessor node by reference. * //**************************************************************** template <class ItemType> void BinTreeType<ItemType>::getSucccessor( TreeNode* aNode, ItemType& data) { aNode = aNode->right; while (aNode->left != NULL) aNode = aNode->left; data = aNode->info; } //**************************************************************** // The displayInOrder member function displays the values * // in the subtree pointed to by nodePtr, via inorder traversal. * //**************************************************************** template <class ItemType> void BinTreeType<ItemType>::displayInOrder() { displayInOrder(root); } // Recursive function performing traversal template <class ItemType> void BinTreeType<ItemType>::displayInOrder(TreeNode *nodePtr) { if (nodePtr != NULL) { displayInOrder(nodePtr->left); cout << nodePtr->info << " "; displayInOrder(nodePtr->right); } } //**************************************************************** // The displayPreOrder member function displays the values * // in the subtree pointed to by nodePtr, via preorder traversal. * //**************************************************************** template <class ItemType> void BinTreeType<ItemType>::displayPreOrder() { displayPreOrder(root); } // Recursive function performing traversal template <class ItemType> void BinTreeType<ItemType>::displayPreOrder(TreeNode *nodePtr) { if (nodePtr != NULL) { cout << nodePtr->info << " "; displayPreOrder(nodePtr->left); displayPreOrder(nodePtr->right); } } //**************************************************************** // The displayPostOrder member function displays the values * // in the subtree pointed to by nodePtr, via postorder traversal.* //**************************************************************** template <class ItemType> void BinTreeType<ItemType>::displayPostOrder() { displayPostOrder(root); } // Recursive function performing traversal template <class ItemType> void BinTreeType<ItemType>::displayPostOrder(TreeNode *nodePtr) { if (nodePtr != NULL) { displayPostOrder(nodePtr->left); displayPostOrder(nodePtr->right); cout << nodePtr->info << " "; } } //**************************************************************** // This function recursively traverses the tree and increments * // a counter at each node "visit" to count the total number of * // data nodes in the tree. * //**************************************************************** template<class ItemType> int BinTreeType<ItemType>::numberOfNodes() { return countNodes(root); } // Private function performing recursive count template<class ItemType> int BinTreeType<ItemType>::countNodes(TreeNode* tree) { if (tree == NULL) return 0; else return countNodes(tree->left) + countNodes(tree->right) + 1; } //****************************************************************** // This function replicates a tree as part of the copy constructor * // and overloaded assignment operations. * //****************************************************************** template<class ItemType> void BinTreeType<ItemType>::copyTree(TreeNode*& copy, const TreeNode* origTree) { if (origTree == NULL) // Handle case of empty tree copy = NULL; else { copy = new TreeNode; copy->info = origTree->info; copyTree(copy->left, origTree->left); copyTree(copy->right, origTree->right); } } //****************************************************************** // Function checking maximum depth below current node //****************************************************************** // Public function initiating count and returning total to main // function call template<class ItemType> int BinTreeType<ItemType>::treeDepth() { int depth = getDepth(root) - 1; return depth; } template<class ItemType> int BinTreeType<ItemType>::getDepth(TreeNode* tree) { if (tree == NULL) return 0; else { // Get depths below current node int leftDepth = getDepth(tree->left); int rightDepth = getDepth(tree->right); // Return max depth of subtrees plus one for "this" node if ( leftDepth > rightDepth) return leftDepth + 1; else return rightDepth + 1; } } #endif

Week 12 In Class Assignemnts C++/binTreeType1.h

// Specification file for the BinTreeType class // PRECONDITION for use of this class: // Data type defining tree node "info" must have operators // '<', 'cout', and ==', or they must be overloaded #ifndef BINARYTREE_H #define BINARYTREE_H #include <iostream> using namespace std; template <class ItemType> class BinTreeType { private: struct TreeNode { ItemType info; TreeNode *left; TreeNode *right; }; TreeNode *root; // Overloaded functions for recursive actions void insert(TreeNode *&, TreeNode *&); void deleteIt(ItemType, TreeNode *&); void makeDeletion(TreeNode *&); void destroySubTree(TreeNode *); void getSucccessor( TreeNode* aNode, ItemType& data); // Recursive functions for various utility operations int countNodes(TreeNode* tree); int getDepth(TreeNode* tree); public: BinTreeType(); // Constructor BinTreeType(BinTreeType& origTree); // Copy constructor void operator= (BinTreeType& origTree); // Overloaded assignment operator ~BinTreeType(); // Destructor // Tree data insertion, deletion, and searching void insertNode(ItemType); bool searchNode(ItemType); void deleteNode(ItemType); // Utilities for tree operations int numberOfNodes(); // Count nodes in tree int treeDepth(); }; //************************************************************* //************************************************************* // Implementation file for the BinTreeType class //************************************************************* //************************************************************* // Constructor template <class ItemType> BinTreeType<ItemType>::BinTreeType() { root = NULL; } // Copy constructor - Utilizes recursive utility function // copyTree to actually replicate original tree template <class ItemType> BinTreeType<ItemType>::BinTreeType(BinTreeType<ItemType>& origTree) { copyTree(root, origTree.root); } // Overloaded assignment operator - Utilizes recursive utility function // copyTree to actually replicate original tree template <class ItemType> void BinTreeType<ItemType>::operator= (BinTreeType<ItemType>& origTree) { destroySubTree(root); // Eliminate any existing nodes in target copyTree(root, origTree.root); // Copy source to target as part of assignment } // Destructor template <class ItemType> BinTreeType<ItemType>::~BinTreeType() { destroySubTree(root); } //************************************************************* // insert accepts a TreeNode pointer and a pointer to a node. * // The function inserts the node into the tree pointed to by * // the TreeNode pointer. This function is called recursively. * //************************************************************* template <class ItemType> void BinTreeType<ItemType>::insert(TreeNode *&nodePtr, TreeNode *&newNode) { if (nodePtr == NULL) nodePtr = newNode; // Insert the node. else if (newNode->info < nodePtr->info) insert(nodePtr->left, newNode); // Search the left branch else insert(nodePtr->right, newNode); // Search the right branch } //********************************************************** // insertNode creates a new node to hold num as its value, * // and passes it to the insert function. * //********************************************************** template <class ItemType> void BinTreeType<ItemType>::insertNode(ItemType num) { TreeNode *newNode; // Pointer to a new node. // Create a new node and store num in it. newNode = new TreeNode; newNode->info = num; newNode->left = newNode->right = NULL; // Insert the node. insert(root, newNode); } //*************************************************** // destroySubTree is called by the destructor. It * // deletes all nodes in the tree. * //*************************************************** template <class ItemType> void BinTreeType<ItemType>::destroySubTree(TreeNode *nodePtr) { if (nodePtr != NULL) { if (nodePtr->left != NULL) destroySubTree(nodePtr->left); if (nodePtr->right != NULL) destroySubTree(nodePtr->right); delete nodePtr; } } //*************************************************** // searchNode determines if a value is present in * // the tree. If so, the function returns true. * // Otherwise, it returns false. * //*************************************************** template <class ItemType> bool BinTreeType<ItemType>::searchNode(ItemType item) { TreeNode *nodePtr = root; while (nodePtr != NULL) { if (nodePtr->info == item) return true; else if (item < nodePtr->info) nodePtr = nodePtr->left; else nodePtr = nodePtr->right; } return false; } //********************************************** // Function deleteNode triggers the chain of * // recursive calls to search for and delete * // target node. * //********************************************** template <class ItemType> void BinTreeType<ItemType>::deleteNode(ItemType item) { deleteIt(item, root); } //*********************************************** // Function deleteIt recursively searches for * // the item to delete and calls function * // makeDeletion to perform the actual deletion. * //*********************************************** template <class ItemType> void BinTreeType<ItemType>::deleteIt(ItemType item, TreeNode *&nodePtr) { if (item < nodePtr->info) deleteIt(item, nodePtr->left); else if (item > nodePtr->info) deleteIt(item, nodePtr->right); else makeDeletion(nodePtr); } //*********************************************************** // makeDeletion takes a reference to a pointer to the node * // that is to be deleted. The node is removed and the * // branches of the tree below the node are reattached. * //*********************************************************** template <class ItemType> void BinTreeType<ItemType>::makeDeletion(TreeNode *&nodePtr) { TreeNode *tempNodePtr; // Temporary pointer, used for deletion ItemType data; if (nodePtr->right == NULL) // If no right child exists { tempNodePtr = nodePtr; nodePtr = nodePtr->left; // Then reattach the left child delete tempNodePtr; } else if (nodePtr->left == NULL) // If no left child exists { tempNodePtr = nodePtr; nodePtr = nodePtr->right; // Then reattach the right child delete tempNodePtr; } else // If the node has two children { // Get data for immediate successor (largest node in right subtree) getSucccessor(nodePtr,data); // Move information from successor node to target node nodePtr->info = data; deleteIt(data, nodePtr->right); // And delete successor node } } //**************************************************************** // This function scans for the succeeding node in order within * // a binary tree. It moves the the right child, and then moves * // down the chain of left children until NULL is reached. It * // returns the data at the predecessor node by reference. * //**************************************************************** template <class ItemType> void BinTreeType<ItemType>::getSucccessor( TreeNode* aNode, ItemType& data) { aNode = aNode->right; while (aNode->left != NULL) aNode = aNode->left; data = aNode->info; } //**************************************************************** // This function recursively traverses the tree and increments * // a counter at each node "visit" to count the total number of * // data nodes in the tree. * //**************************************************************** template<class ItemType> int BinTreeType<ItemType>::numberOfNodes() { return countNodes(root); } // Private function performing recursive count template<class ItemType> int BinTreeType<ItemType>::countNodes(TreeNode* tree) { if (tree == NULL) return 0; else { // Write number of nodes while this recursive execution running int num = countNodes(tree->left) + countNodes(tree->right) + 1; cout << "Node info: " << tree->info << " returning " << num << endl; return num; } } // Public function initiating count and returning total to main // function call template<class ItemType> int BinTreeType<ItemType>::treeDepth() { return 0; } // Private function checking maximum depth below current node template<class ItemType> int BinTreeType<ItemType>::getDepth(TreeNode* tree) { return 0; } #endif

Week 12 In Class Assignemnts C++/depthAnalysis.cpp

Week 12 In Class Assignemnts C++/depthAnalysis.cpp

// This demonstrates the depth of binary search trees generated with random
// keys.  The depth of each tree is directly related to the search efficiency
// for the tree.
// Range of random numbers is 0 ... 32,767^2  ( rand() * rand() )

#include   < fstream >
#include   < iostream >
#include   < iomanip >
#include   < ctime >
#include   < cstdlib >
using   namespace  std ;

#include   "binTreeType1.h"

const   int  START   =   1 ;          // Define range for simulation
const   int  FINISH  =   1000000 ;

int  main ()
{     
    srand ( time ( 0 ));              // set seed with clock function
    
     BinTreeType < int >  theTree ;

     int  valueToAdd ;
    
     // Write report headings
    cout  <<   "Tree Nodes   Tree Depth"   <<  endl ;

     // Generate given number of random inserts; then multiply by 10 and repeat
     for   ( int  numberInserts  =  START ;  numberInserts  <=  FINISH ;  numberInserts  *=   10 )
     {
         for   ( int  i  =   1 ;  i  <=  numberInserts ;  i ++ )
         {
           valueToAdd  =  rand ()   *  rand ();      // Insert random integers
           theTree . insertNode ( valueToAdd );
         }
    
         // Write output line
        cout  <<  setw ( 10 )   <<  numberInserts 
              <<  setw ( 10 )   <<  theTree . treeDepth ()   <<  endl ;
     }

    return   0 ;
}

Week 12 In Class Assignemnts C++/SmallAssignment1.pdf

CST 280 In-Class Practice – Week 12 Access the following files from the course Week 12 practice file access page (using code bn23):

binTreeType.h depthAnalysis.cpp.

Add following functions to the tree class treeDepth()and getDepth().

template<class ItemType> int BinTreeType<ItemType>::treeDepth() { return getDepth(root) - 1; // Subtracting root as level zero } // Private function checking maximum depth below current node template<class ItemType> int BinTreeType<ItemType>::getDepth(TreeNode* tree) { if (tree == NULL) return 0; else { // Get depths below current node int leftDepth = getDepth(tree->left); int rightDepth = getDepth(tree->right); // Return max depth of subtrees plus one for "this" node if ( leftDepth > rightDepth) return leftDepth + 1; else return rightDepth + 1; } }

The provided driver program depthAnalysis.cpp will demonstrate typical tree depths based on the number of nodes entered. This program generates a variety of tree sizes using random integers before returning the maxium depth of the tree. Deliverables: The source code and output.

Week 12 In Class Assignemnts C++/SmallAssignment2.pdf

CST 280 2 pts In-Class Assignment 11b Assume the following list of elements (ordered alphabetically) are inserted into a binary search tree in the given sequence. H C R A S Q B F Z M D X a) Sketch the initial resulting binary search tree:

b) Referring to the tree in (a) describe the sequence of "visits" to nodes as the tree is traversed in:

PreOrder: InOrder: PostOrder:

c) Sketch the tree after all of the following changes are made (assuming the strategy for deletion is used that was discussed in class):

Insert G Delete Q Insert I Insert Y Delete R Delete H Delete C Insert H

Tree from part (c):

d) Referring to the tree in (c) describe the sequence of "visits" to nodes as the tree is traversed in:

PreOrder: InOrder: PostOrder:

e) Access the following files from the course web page: binTreeType.h, and text file testTree.cpp. Verify your results using the tree class presented in class.

Deliverables: This page, your source code and output.

Week 12 In Class Assignemnts C++/testTree.cpp

Week 12 In Class Assignemnts C++/testTree.cpp

// This program is a test driver to demonstrate various functions of
// a binary search tree.

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

#include   "binTreeType.h"

int  main ()
{     
    
     BinTreeType < char >  theTree ;
    
     // Insert various characters into tree
    theTree . insertNode ( 'N' );
    theTree . insertNode ( 'G' );
    theTree . insertNode ( 'C' );
    theTree . insertNode ( 'A' );
    theTree . insertNode ( 'D' );
    theTree . insertNode ( 'L' );
    theTree . insertNode ( 'K' );
    theTree . insertNode ( 'S' );
    theTree . insertNode ( 'P' );
    theTree . insertNode ( 'Q' );
    theTree . insertNode ( 'X' );
    theTree . insertNode ( 'U' );
    theTree . insertNode ( 'Z' );
   
     // Test with deletes and inserts
    theTree . deleteNode ( 'K' );
    theTree . deleteNode ( 'P' );
    theTree . deleteNode ( 'X' );
    theTree . deleteNode ( 'N' );

     // Test searching - Find 'Q'
     if   ( theTree . searchNode ( 'Q' ))
       cout  <<   "Q found in tree"   <<  endl ;
     else
       cout  <<   "Q not found in tree"   <<  endl ;
    
     // Test searching - Find 'M'
     if   ( theTree . searchNode ( 'M' ))
       cout  <<   "M found in tree"   <<  endl ;
     else
       cout  <<   "M not found in tree"   <<  endl  <<  endl ;

     // Display tree in various traveral orders
    cout  <<   "Pre-Order"   <<  endl ;
    theTree . displayPreOrder ();
    cout  <<  endl  <<  endl ;
    
    cout  <<   "In-Order"   <<  endl ;
    theTree . displayInOrder ();
    cout  <<  endl  <<  endl ;

    cout  <<   "Post-Order"   <<  endl ;
    theTree . displayPostOrder ();
    cout  <<  endl  <<  endl ;    
        
     // Display number of nodes
    cout  <<   "This tree has "   <<  theTree . numberOfNodes ()   <<   " nodes"   <<  endl ;
    cout  <<   "This tree has max depth of "   <<  theTree . treeDepth ()   <<  endl ;

     return   0 ;    // End program
}