0

I need some help to why an insertion in a bst doesn't work on the following code. Is there some concept on how java passes parameters that I do not know?

 public void insert(int input){
        insert(root, input);
}
private void insert(Node node, int input){
    Node new_node = new Node(input);
    if (node == null) {
        node = new_node;
        }
    else if (input == node.data) {
        System.out.println("input exists");
        }
    else {
        if (input < node.data) {
            insert(node.left, input);
        }
        else{
            insert(node.right, input);
        }
    }
}

2 Answers2

0

Try to insert like this in the BST

    public void insert(int val) {
        root = put(root, val);
    }

    private Node insert(Node node, int val) {
        if (node == null)
            return new Node(val);
        int cmp = Integer.valueOf(val).compareTo(node.data);
        if (cmp < 0)
            node.left = insert(node.left, val);
        else if (cmp > 0)
            node.right = insert(node.right, val);
        else
            node.data = val;
        return node;
    }
0xh3xa
  • 4,801
  • 2
  • 14
  • 28
0

Reassigning the parameter node won't change anything about the thing you passed to the method (node.left or node.right):

node = new_node;

Because node stores a reference to the Node object (that you want to replace). The assignment only changes the reference so that it refers to another object. See this for more info.

You could reassign node.left and node.right instead:

Node new_node = new Node(input);
if (input == node.data) {
    System.out.println("input exists");
} else if (input < node.data) {
    if (node.left != null) {
        insert(node.left, input);
    } else {
        node.left = new_node;
    }
}
else{
    if (node.right != null) {
        insert(node.right, input);
    } else {
        node.right = new_node;
    }
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313