Implement a Binary Search Tree. Your class should be templated so that it can st
ID: 3732324 • Letter: I
Question
Implement a Binary Search Tree. Your class should be templated so that it can store any sort of data. The constructor for the class should take a comparison function as a function pointer as a parameter. This function will take 2 items as parameters of the type specified in the template (passed by constant reference), and return an int (-1 if the first item is less than the second item, 0 if they are equal, 1 if item 1 is greater than item 2). You should use this function for comparisons when an item is inserted into the tree, or when searching for an item. Your Binary Search Tree should have functions for inserting, removing, and searching for data. As with the List implementations, the search in the Binary Search Tree should take an item as a parameter, and return an item if found. If not found, the function should throw an exception indicating that. For Insert, the function should take an item as a parameter and throw an exception if the item is a duplicate. Remove should take an item as a parameter, and throw an exception if the item was not found. You should use the delete by copy. with c++
Explanation / Answer
#include <iostream>
template <class T>
class Tree
{
struct TreeNode
{
T data;
TreeNode * left;
TreeNode * right;
TreeNode(T val):data(val),left(NULL),right(NULL)
{
}
};
TreeNode * root;
void print(TreeNode*);
void freeMemory(TreeNode*);
public:
Tree();
~Tree();
void insert(T);
void print();
};
template <class T>
Tree<T>::Tree():root(NULL){}
template <class T>
Tree<T>::~Tree()
{
freeMemory(root);
}
template <class T>
void Tree<T>::freeMemory(Tree::TreeNode *node)
{
if (node==NULL)
return;
if (node->left)
freeMemory(node->left);
if (root->right)
freeMemory(node->right);
delete node;
}
template <class T>
void Tree<T>::insert(T val)
{
TreeNode * treeNode = NULL;
try
{
treeNode = new TreeNode(val);
} catch (std::bad_alloc &exception)
{
std::cerr << "bad_alloc caught: " << exception.what() << std::endl;
EXIT_FAILURE;
}
TreeNode *temp=NULL;
TreeNode *prev=NULL;
temp = root;
while(temp)
{
prev = temp;
if (temp->data < treeNode->data)
temp = temp->right;
else
temp = temp->left;
}
if (prev==NULL)
root = treeNode;
else
{
if (prev->data<treeNode->data)
prev->right = treeNode;
else
prev->left = treeNode;
}
}
template <class T>
void Tree<T>::print(TreeNode *root)
{
if (root==NULL)
return ;
print(root->left);
std::cout << root->data << std::endl;
print(root->right);
}
template <class T>
void Tree<T>::print()
{
print(root);
}
int main()
{
Tree<int> tree;
tree.insert(14);
tree.insert(12);
tree.insert(6);
tree.insert(17);
tree.insert(8);
tree.print();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.