I've been working on a binary search tree and I've written out most of what I think the code should look like but I can't test it because of an error I'm getting. I have no idea if what I have is even correct. My professor gave us the class, the structure, and the Main to use. My problem is in the getRoot(void) function. When I try compiling my code, it tells me that ptr is undeclared. I can't figure out what to change. I would appreciate it if someone could help me.
Here's my code:
#include <iostream>
using namespace std;
///////////////////////////////////////////////
// tnode structure
typedef struct tnode
{
int data;
struct tnode *leftChild;
struct tnode *rightChild;
}TNODE;
///////////////////////////////////////////////
//Binary search tree class
class BSTree
{
public:
BSTree(void);
void addNode(int data);
void findNode(TNODE *ptr, int data);
void printTree(TNODE *ptr, int level);
TNODE *getRoot(void);
private:
TNODE* ptr;
};
///////////////////////////////////////////////
//main
int main()
{
BSTree mytree;
int level = 1;
TNODE* tree;
int i, numbers[] = {9, 7, 15, 5, 8, 14, 20, 4};
for(i = 0; i < 8; i++)
mytree.addNode(numbers[i]);
mytree.printTree(mytree.getRoot(), level);
return 0;
}
////////////////////////////////////////////////
//methods
BSTree::BSTree()
{//constructor
ptr = NULL; // indicates an empty list
}
void BSTree::addNode(int data)
{//adds root to the tree.
if(ptr == NULL)
{
ptr->data = data;
ptr->leftChild = NULL;
ptr->rightChild = NULL;
}
else
findNode(ptr, data);
}
void BSTree::findNode(TNODE *ptr, int data)
{//finds where to add the node. Traverse through tree then add the node.
if ( data < ptr->data )
{
findNode(ptr->leftChild, data);
}
else if (data > ptr->data)
{
findNode(ptr->rightChild, data);
}
else if(ptr->data == NULL)
{
ptr->data = data;
ptr->leftChild = NULL;
ptr->rightChild = NULL;
}
}
void BSTree::printTree(TNODE *ptr, int level)
{//prints out the tree on its side
if(ptr != NULL)
{
printTree(ptr->rightChild, level + 1);
for(int i = 0; i < 3 * level; i++)
cout << " ";
cout << ptr -> data << endl;
printTree(ptr->leftChild, level + 1);
}
}
TNODE *getRoot(void)
{//returns the root pointer
return ptr;
}