Hey guys,
I've been messing around trying to learn binary trees and have created a simple program to get the month and number of days in a month to be inserted into the tree then displayed. I am getting a successful build, however, when it launches the terminal window the program crashes. I can't seem to find my error. Hopefully someone in the community can help me.
Here is my BINARYTREE.h file:
#ifndef BINARY_TREE
#define BINARY_TREE
#include <iostream>
#include <string>
using namespace std;
class BinaryTree
{
private:
struct Node
{
string monthName;
int noDaysInMonth;//monthID is used strictly for
Node *left, *right;
};
Node *root;
public:
BinaryTree();
void createNode(string month, int days){ createNode(root, month, days); }
void createNode(Node *&, string, int);
void displayAlphabetically(){ displayAlphabetically(root); }
void displayAlphabetically(Node *);
void destroyTree(Node *&);
~BinaryTree(){ destroyTree(root); }
};
#endif
The matching implementation file BINARYTREE.cpp:
#include "BINARY_TREE.h"
BinaryTree :: BinaryTree()
{
root = NULL;
}
void BinaryTree :: createNode(Node *&treeTop, string month, int days)
{
if(treeTop != NULL)
{
treeTop = new Node;
treeTop -> monthName = month; treeTop -> noDaysInMonth = days;
treeTop -> left = NULL; treeTop -> right = NULL;
}
else if(month < treeTop -> monthName)
{
createNode(treeTop -> left, month, days);
}
else
{
createNode(treeTop -> right, month, days);
}
}
void BinaryTree :: displayAlphabetically(Node *treeTop)
{
if (treeTop != NULL)
{
displayAlphabetically(treeTop -> left);
cout << treeTop -> monthName << " - " << treeTop -> noDaysInMonth << " days" << endl;
displayAlphabetically(treeTop -> right);
}
}
void BinaryTree :: destroyTree(Node *&treeTop)
{
if (treeTop != NULL)
{
destroyTree(treeTop -> left); destroyTree(treeTop -> right);
delete treeTop; treeTop = NULL;
}
}
Lastly, this is how I call it from main:
#include "BINARY_TREE.h"
int main()
{
string months[] = {"Dec", "Nov", "Oct", "Sep", "Aug", "Jul",
"Jun", "May", "Apr", "Mar", "Feb", "Jan"};
int noDays[] = {31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 29, 31};
BinaryTree h;
for(int i = 0; i < 12; i++)
{
h.createNode(months[i], noDays[i]);
}
h.displayAlphabetically();
return 0;
}