Skip to content
Advertisement

Binary Search Tree’s add method in Java

I have a piece of code for inserting a node to Binary Search Tree in Java like:

JavaScript

Why doesn’t my information print when I run the program? Thank you for answering my question!!

Advertisement

Answer

You don’t update the left/right pointers when the recursion returns. Also, the local variable head is different from the instance variable. Hence, the new nodes you create are thrown away when the method returns.

Here is one way to do it.

The private add method returns the updated node which gets (re-)assigned when the recursion returns.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement