0
public void addNodes(int[] keys){
        //TODO
            add(keys, root);
    }

    private void add(int[] keys, Node auxRoot){
        if(auxRoot == null){
            System.out.println("Root " + keys[0]);
            auxRoot = new Node(keys[0]);
            int[] newKeys = new int[keys.length-1];
            for(int i =  0; i < keys.length-1; i++){
                newKeys[i] = keys[i+1];
            }
            add(newKeys, auxRoot);
        } else if(auxRoot != null && keys[0] < auxRoot.key){
            System.out.println("Left " + keys[0]);
            if(auxRoot.left == null){
                auxRoot.left = new Node(keys[0]);
                if (keys.length > 1) {
                    int[] newKeys = new int[keys.length - 1];
                    for (int i = 0; i < keys.length - 1; i++) {
                        newKeys[i] = keys[i + 1];
                    }
                    add(newKeys, auxRoot);
                }
            } else if(auxRoot.left != null){
                add(keys, auxRoot.left);
            }

        } else if(auxRoot != null && keys[0] > auxRoot.key){
            System.out.println("Right " + keys[0]);
            if(auxRoot.right == null){
                auxRoot.right = new Node(keys[0]);
                if (keys.length > 1) {
                    int[] newKeys = new int[keys.length - 1];
                    for (int i = 0; i < keys.length - 1; i++) {
                        newKeys[i] = keys[i + 1];
                    }
                    add(newKeys, auxRoot);
                }
            } else if(auxRoot.right != null){
                System.out.println("keep going");
                add(keys, auxRoot.right);
            }
        }
    }

I made this add auxiliary method for the addNode, for some reason, when I print out the key of the root it still null. Why is this the case? I am passing the root to the add auxiliary method. I understand is pass-by-value. How do I change this method to make root have a value.

Asen Christov
  • 848
  • 6
  • 21
Loc
  • 5
  • 2
  • 2
    Changing the value of the `auxRoot` won't do anything to the variable you used as a parameter to your method. Java is purely pass-by-value, and makes a copy of the object reference (in this case `null`) and gives it to the `add()` method. You cannot affect the actual variable in the invoking code. – azurefrog Jul 07 '16 at 18:22
  • No wonder. How would I go about changing this code, now? I was thinking of returning each node, instead. – Loc Jul 07 '16 at 18:26
  • `root = add(keys, root);` In goes the old root, out can come a new root value. The same holds for left and right, but there you do assign to them. – Joop Eggen Jul 11 '16 at 14:09

0 Answers0