Hi everyone,
I'm trying to implement a binary search tree but im having troubles with my Add function. The add function is supposed to take a pointer to a variable and add it to the tree.
To begin with, the add function is called from Insert, which sends the new variable to be added and a pointer to the root node, which is initially null. Inside the Add function it checks to see if the passed pointer is null, if it is then it creates a new pointer to a node with the passed value in it, and then assigns the new pointer to the passed pointer.
The first time this function is called should mean that the root pointer now points to the newly created node. However when i try and traverse the tree it root pointer is null.
Can someone please give me some direction, any help will be greatly appreciated.
Thanks
#ifndef CTREE_H
#define CTREE_H
#include <cstdio>
#include "CTNode.h"
using namespace std;
using namespace oneill_ctnode1;
namespace oneill_ctree1
{
template <typename Item>
class CTree
{
public:
// Constructors
CTree();
CTree(Item* value);
// Destructor
~CTree();
// Mutators
bool Insert(Item*);
// Query
void traverse();
private:
void print(CTNode<Item>*);
void Add(Item*,CTNode<Item>*);
CTNode<Item>* root;
CTNode<Item>* curr;
};
}
#include "CTree.template"
#endif
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include "CTNode.h"
using namespace std;
using namespace oneill_ctnode1;
namespace oneill_ctree1
{
template <typename Item>
CTree<Item>::CTree()
{
root = NULL;
}
template <typename Item>
CTree<Item>::CTree(Item* value)
{
CTNode<Item>* temp = new CTNode<Item>(value,NULL,NULL);
root = temp;
}
template <typename Item>
CTree<Item>::~CTree()
{
}
template <typename Item>
bool CTree<Item>::Insert(Item* value)
{
//cout <<"Before: " <<root << endl;
Add(value,root);
//cout <<"After: " <<root << endl;
return 1;
}
template <typename Item>
void CTree<Item>::Add(Item* value,CTNode<Item>* node)
{
if (node == NULL)
{
CTNode<Item>* temp = new CTNode<Item>(value,NULL,NULL);
cout << "Node before: "<<node<<endl;
node = temp;
cout << "Node after: "<<node<<endl;
}
else
{
if (*value < node->get_data())
{
Add(value, node->get_left());
//cout << "To the left"<<endl;
}
else
{
if (*value > node->get_data())
{
Add(value, node->get_right());
//cout << "To the right"<<endl;
}
else
{
node->set_count((node->get_count())+1);
}
}
}
}
template <typename Item>
void CTree<Item>::traverse()
{
CTNode<char>* temp;
//print(root);
if (root == NULL)
cout <<"Root is NULL"<<endl;
else
cout<< root->get_data() <<endl;
temp = root->get_left();
if (temp == NULL)
cout <<"Temp left is NULL"<<endl;
else
cout<< temp->get_data() <<endl;
temp = root->get_right();
if (temp == NULL)
cout <<"Temp right is NULL"<<endl;
else
cout<< temp->get_data() <<endl;
}
template <typename Item>
void CTree<Item>::print(CTNode<Item>* node)
{
if(node != NULL)
{
print(node->get_left());
cout << (node->get_data()) <<endl;
print(node->get_right());
}
}
}