So I finished my List exercise and went ahead with Binary Trees. My code thus far:
Tree.h
#include "Node.h"
class Tree
{
private:
int mCount;
Node *root;
public:
Tree();
~Tree();
void insert(int, Node *);
};
Tree.cpp
void Tree::insert(int data, Node *node)
{
if( root == 0 )
{
Node *temp = new Node;
temp->setData(100);
temp->setRight(0);
temp->setLeft(0);
root = temp;
}
else
{
if( data > root->getData() )
return insert( data, root->getRight() );
else
return insert( data, root->getLeft() );
}
}
main.cpp
int main(int argc, char** argv)
{
Tree *tree = new Tree;
tree->insert( 100, 0 );
std::cin.get();
return 0;
}
I hope this is sufficient code. Node
and Tree
are two separate classes. I'm having difficulties wrapping my head around the recursion.
I have Node *root
defined in my Tree class to have a root node at the top of the tree. However, the way I see it, when I call tree->insert
insert in main, I don't have to specify any node. The root from the Tree class will do all the looking. However, when I'm in the code and need to recur, then I am suddenly a parameter short, as shown above.
My solution was to just place the parameter Node *node
in the argument list for insert()
anyway and call it with a 0
from main. I would also need to call tree->display(0);
as parameter for Node *node
as well.
This seems hackish. Am I missing something obvious?