I have created a program which contains a class Node, for representing a binary tree of any type(template).
In my Node.h class, I have two constructors, however I am not sure if I implemented both of them correctly. Initialising the values within the constructors has confused me. In my main.cpp file, I have a setUpTree function. My program executes now, but doesnt print the tree that is set up.
I have tried for hours trying to fix this but to no ends. I am not really experienced with C++, pointers, constructors etc yet.
I would appreciate it if anyone could help me fix my code so that the setUpTree function works, and also the printTree method.
Thanks
Node.h Class:
#ifndef NODE_H
#define NODE_H
#include <iostream>
#include <string>
using namespace std;
//an object of type node holds 3 things
// - an item (of type t)
// - a left subtree
// - a right subtree
template<typename T>
class Node {
public:
Node(T item); //constructor to create a leaf node
Node(T item, Node *lft, Node *rht); //constructor which creates an internal node
~Node(); //Destructor
//public data member functions:
bool searchTree(T key);
void printTree();
private:
//private data member functions:
Node* left;
Node* right;
T item;
};
//constructor
template<typename T>
Node<T>::Node(T i, Node<T> *lft, Node<T> *rht) {
item = i;
left = NULL;
right = NULL;
}
//constructor
template <typename T>
Node<T>::Node(T i) { //should i be a parameter here?
item = i; //is this right for this constructor?
}
//destructor
template <typename T>
Node<T>::~Node() {
delete left;
delete right;
//delete;
}
//print tree method
template <typename T>
void Node<T>::printTree() {
if (left != NULL) {
left->printTree();
cout << item << endl;//alphabetical order
}
if (right != NULL) {
right->printTree();
//cout << item << endl; //post order
}
}
//search Tree method
template <typename T>
bool Node<T>::searchTree(T key) {
bool found = false;
if (item == key) {
return true;
}
if (left != NULL) {
found = left->searchTree(key);
if (found) return true;
}
if (right != NULL) {
return right->searchTree(key);
}
return false; //if left and right are both null & key is not the search item, then not found == not in the tree.
}
#endif
Main.cpp Class:
#include "Node.h"
#include <iostream>
using namespace std;
//set up tree method
Node<string> *setUpTree() {
Node<string> *s_tree =
new Node<string>("Sunday",
new Node<string>("monday",
new Node<string>("Friday"),
new Node<string>("Saturday")),
new Node<string>("Tuesday",
new Node<string>("Thursday"),
new Node<string>("Wednesday")));
return s_tree;
}
int main() {
Node<string> *s_tree;
s_tree = setUpTree(); //call setUpTree method on s_tree
cout << "Part 2 :Printing tree values: " << endl;
s_tree->printTree(); //call print tree method
cout << endl;
//search for range of tree values
//searchTree(s_tree, "Sunday");
//searchTree(s_tree, "Monday");
return 0;
}