I’m doing a small Java work on Binary Search Tree but when I’m implementing the recursive insert of a node into the tree and display it, I don’t get anything. I’ve been on it for a while now, I don’t know for sure but I think it’s a pass-by-reference problem.
Here’s my code:
public class BST {
private BSTNode root;
public BST() {
root = null;
}
public BSTNode getRoot() {
return root;
}
public void insertR( BSTNode root, Comparable elem ) {
if ( root == null ) {
root = new BSTNode( elem );
}
else {
if ( elem.compareTo( root.element ) < 0 ) {
insertR( root.left, elem );
} else {
insertR( root.right, elem );
}
}
}
public void printInOrder (BSTNode root) {
if (root != null) {
printInOrder(root.left);
System.out.println(root.element);
printInOrder(root.right);
}
}
}
class BSTNode {
protected Comparable element;
protected BSTNode left;
protected BSTNode right;
protected BSTNode ( Comparable elem ) {
element = elem;
left = null;
right = null;
}
}
I executed a series of insertR with the root being the node to insert into and the elem is a string but it doesn’t print anything out, as if the tree was not filled in at all. I’m sure it’s problem with my recursive insert but I’m not sure where, I need to use a recursive insert method that returns nothing which I think is impossible.
Any help would be great.
Your left, right element of the BSTNodes are null. You need to create them before inserting into it. Otherwise they create an empty hanging BSTNode() and insert it, without connecting to the rest of the tree.
You can change the lines,
to