I am wandering what i have done wrong, could anyone help me please? I am trying to make a generic BST, with DDL(doubly linked list) data structure. The thing is my ADT is initalisated since my isEmpty method works, but my public addNewElement which sues private insert do not work. Any help and advices are welcome.
Interface:
public interface SortedSetBST <type> extends Iterable<type>{
void addNewElement(Comparable<type> newElement);
}
ADT:
package adt;
import java.util.Iterator;
import java.util.Iterator;
import interfaces.SortedSetBST;
import exceptions.*;
public class BinarySearchTree <type> implements SortedSetBST<type> {
BinaryNode <type> root;
int size;
@Override
public void addNewElement(Comparable <type> newElement) {
insert(newElement, root);
}
protected BinaryNode <type> insert( Comparable <type> x, BinaryNode <type> t ) {
if( t == null )
t = new BinaryNode( x );
else if( x.compareTo( t.element ) < 0 )
t.left = insert( x, t.left );
else if( x.compareTo( t.element ) > 0 )
t.right = insert( x, t.right );
else
throw new DuplicateItemException( x.toString( ) ); // Duplicate
return t;
}
class BinaryNode<type> {
type element; // The data in the node
BinaryNode<type> left; // Left child
BinaryNode<type> right; // Right child
// Constructors
BinaryNode( type theElement ) {
element = theElement;
left = right = null;
}
}
class App
public class App {
public static void main(String [] args){
System.out.println(" Main:");
BinarySearchTree <String> db = new BinarySearchTree<String>();
if(db.isEmpty() == true){
System.out.println(".db empty!");
}
db.addNewElement("unu");
db.addNewElement("doi");
db.addNewElement("trei");
System.out.println(db.getSize());
}
}
output:
Main:
.db empty!
0
This is clear.
In “insert” you are checking if t is null. If this is the case, you initialize the parameter t with an instance of BinaryNode thinking you would also update root when it is first passed in being “null”. But “null” is “null” in Java and not a C-style-address as you might think!
Then you return this parameter but the return value is lost in “addNewElement”.
How to do this right: