Binary search tree doubt

https://ide.codingblocks.com/s/63617
if i put <= in line 22 or >= in line 25 if shows runtime error. without putting equal to operator its showing correct output. why is it so?

Hi Simran, first of all you cannot use both <= and >= at the same time. >= or <= will be used to handle duplicates in a BST. When you are handling duplicates then you need to take care of them either on left side or right side. Depending on this chose to put >= or <= depending on your choice.
But in your code if you put a <= in line 22 then you may notice that you code will enter an infinite loop.
You just need to remove that infinite loop and it will be done by changing “if” to “else if” in line 22 and 25.

I hope now you understand where this went wrong :slight_smile:

1 Like

I didnt understand how is it causing infinite loop?

Hi Simran! let’s put <= in line 22. So your code goes like this:

node* insertBst(node *root, int d){
if ( root == NULL)
root= new node(d);

if ( d <= root->data){
root->left= insertBst(root->left, d);
}
if( d> root->data){
root->right= insertBst(root->right, d);
}

return root;
}

Now, initially the tree is empty i.e. root = NULL. When we call :

root= insertBst(root, d); //Line 38 in your code

Now it goes to insertBST function
As root == NULL so
root = new node(d) will get executed.
after this happens it will go to the next if
i.e. to if ( d <= root->data){
just now we created root node whose data = d
=> ( d <= root-> data ) is true
so the part in that if block will also get executed.

i.e. it passes root-> left , d to insertBST() function
the same thing happens again and again and never terminates.

// Try putting
cout << “hi” ;
// in your code and then run it you will see what is happening on your output screen.

Basically this is happening :

only the left side of tree is getting built with data as d. This is the infinite loop it gets stuck into.

Hope this helps :slight_smile:

1 Like