I'm trying to input numbers in a binary tree with an array of random integers. But all I get is two numbers, and they are always the same!

From the main:

const int length= 10; // This is used several places, hence the const
int array[length]; // One of the places the length is used

// More code here for inputing one and one number to the tree.
// Not really relevant for the array part.

for(int i =0; i < lengde; i ++)
{
	array[i] = rand() % 50 + 1;
	bintree.ins(array);
}

From the code for binary tree:

void BT::ins(int *number)
{
	tree_node* tree = new tre_node;
	tree_node* parent;
	tree->t = *number;
	tree->l = NULL;
	tree->r = NULL;
	parent = NULL;

	if(isEmpty())
	{
		root = tree;
	} // end if
	else
	{
		tree_node* curr;
		curr = root;

		while(curr)
		{
			parent = curr;
			if(tree->t > curr->t)
			{
				curr = curr>r;
			} // end if
			else
			{
				curr = curr->l;
			} // end else
		} // end while

		if(tree->t < parent->t)
		{
			parent->l = tree;
		} // end if
		else
		{
			parent->r = tree;
		} // end else
	} // end else
} // end method

Where did I go wrong? Why am I only getting two numbers? And the same number? :confused:
(Typos might be from editing from one language to another since it's not originally in english. So ignore regulare Typos.. ;) )

Recommended Answers

All 3 Replies

Call srand((unsigned)time(0)) only once before your first call to rand() . This seeds the random number generator with the current time.
You'll need to include ctime (formerly time.h) for this.

Already done that. That part must not have been copied when I posted the code. Strange... But I do have the

srand(time(0))

and this works fine when I input one singel integer 10 times using a for-loop.

It's just inserting 10 random integers to an array and passing these on to the tree I can't seem to get rigt.

EDIT to the last post!

The error is corrected! I've just been really blond dealing with this problem. Was a silly mistake...

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.