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!

Any particulary reason you're writing procedural code in C++? A better approach would be to create a tree class that handles everything.

Anyways, one major problem you have is that you pass a single pointer to traverse. The pointer in traverse is local to the function, so setting current = new node; Only modifies the pointer in the function.

Have you been reading a tutorial on binary trees? If you have, I think you should re-read it, and possibly find one that is specifically object oriented.

For a full blown implementation of Binary trees in OO C++ see here:

http://library.thinkquest.org/C005618/text/binarytrees.htm

A good way of approaching the problem will be to jot down all the details (like variables, class design, usage etc) which though may seem as a waste of time to you will definately help you in the long run. IF this kind of documentation is made, the coding just becomes mechanical.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.