BST insertion function

So basically i know how BST tree works theoretically but i don't understand how how it operates after the 2nd number is entered in the following code when another data is entered it how can it make a new node and comeback to if statement since after 1st node temp value is not NULL so it shouldn't work
Please can someone explain how this code works
http://tinypic.com/r/11m97c6/8

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  node* Insert(node* temp, int num)
{
   	if ( temp == NULL )
   	{
   		temp = new node;
   		temp->data= num;
      	temp->LTree= NULL;
      	temp->RTree=NULL;
   	}
   	else if(num < temp->data)
      	temp->LTree = Insert(temp->LTree, num);
   	else //if( num >= temp->data)
      	temp->RTree = Insert(temp->RTree,num);
   	return temp;
}
I don't understand your drawing.

> since after 1st node temp value is not NULL
`temp' lives only in the scope of the function.
I suggest you to make a step-by-step run and look at the call stack.

The idea is that you'll traverse the tree until you find a leaf (temp==NULL)


> temp->LTree = Insert(temp->LTree, num);
note the error prone repetition.
If `temp->LTree' is a leaf, it will point to the new node allocated by `Insert()'
If it is not a leaf, then its value does not change
Topic archived. No new replies allowed.