I am trying to create a binary tree. Ultimately I would like a user to be able to insert how deep he or she wants the tree to be and then have my program be able to create the tree at that depth. Root = depth 1 and so on. Here is the code I have.. it doesn't seem to do the right thing. I have set my depth level at a given number for now and have decided to implement the "asking for depth level" later on as it is not as important to me as actually getting the tree to build correctly:
#include <cstdlib>
#include <iostream>
typedef struct node
{
int data;
node *lc;
node *rc;
}node;
int deep = 3;
void traverse(node *current);
using namespace std;
int main(int argc, char *argv[])
{
node *here;
traverse(here);
system("PAUSE");
return EXIT_SUCCESS;
}
void traverse(node *current)
{
deep--;
if(deep != 0)
{
current = new node;
current->data = rand();
}
else
{
deep++;
return;
}
traverse(current->lc);
traverse(current->rc);
deep++;
}
Can anyone tell me what is wrong with this? I seem to run into a road block when the "traverse" function gets called again and it looks like it is trying to create a new node overtop of one that exists... maybe i'm just reading the code wrong.. i don't know. Obviously, you can see i'm doing this recursively. Any help would be much appreciated. Thank You!