NaughtySloth
NaughtySloth

Reputation: 15

Binary Search Tree recursive add

I'm trying to make a recursive add for my BST. The public add method takes an int argument, the private method takes the same int and a Node. This is the code I have so far

 public void add(int i) {

    add(i, root);

}

private void add(int i, Node n) {
    if (root==null){
        root=new Node(i);
    }

    if (i < n.element) {
        if (n.left != null) {
            add(i, n.left);
        } else {
            n.left = new Node(i);
        }
    } else if (i > n.element) {
        if (n.right != null) {
            add(i, n.right);
        } else {
            n.right = new Node(i);
        }
    }
}

I constanly keep getting null pointers, tried debugging as well but there's something flawed in my logic that I can't see.

Upvotes: 1

Views: 3653

Answers (1)

Robert Kock
Robert Kock

Reputation: 6038

When your tree is empty (root=null), you correctly create a new node and assign it to your root variable. But that's all it should do.
Therefore:

if (root==null){
    root=new Node(i);
    return; // DONE!!
}

Or, if you want:

if (root==null){
    root=new Node(i);
}
else if (i < n.element) {
....

Upvotes: 2

Related Questions