传递给方法时未将新节点分配给树

时间:2019-05-24 14:09:02

标签: java binary-search-tree

新节点在通过传递到方法时不分配给树,而是在直接传递而不是传递给方法时起作用。

我制作了Node类和MYBinarySearchTree类。当我在insertIt方法中传递根节点和数据时,它将在运行时给出nullpointerexception。

class Node{
    int data;
    Node left, right;
    Node(int d){
        data = d;
        left = right  = null;
    }
}
class MyBinarySearchTree{
    Node root ;

    MyBinarySearchTree(){
        root = null;
    }

    void insert(int data){
        //root = new Node(data);
        insertIt(root,data);

    }

    static void insertIt(Node node, int data){
        node = new Node(data);

    }

}
class BinarySearchTree{
    public static void main(String[] args) {
        MyBinarySearchTree bst = new MyBinarySearchTree();
        bst.insert(45);
        System.out.println(bst.root.data);

    }
}

上面的代码不起作用。



    void insert(int data){
        root = new Node(data);
        //insertIt(root,data);

    }

    static void insertIt(Node node, int data){
        node = new Node(data);

    }

上面的代码有效

我不了解两者之间的区别,因为在Java对象中是按引用传递的,因此它应该给出相同的结果。

1 个答案:

答案 0 :(得分:1)

这不是真的:

  

因为在Java对象中是通过引用传递的

Java仅按值传递。将 node 传递给 insertIt()方法时,将传递 node 值的副本(引用)。方法 insertIt()创建另一个对象 new Node(data),它具有不同的引用。变量 node 更改其引用(更改为 new Node(data)),而不是对象本身。

在这里,您的函数insertIt()应该像这样:

Node insertIt(int data){
    return new Node(data);
}

在您的insert()函数中:

void insert(int data){
    this.root = insertIt(data);
}

此外,除了创建新的Node外,我不了解insertIt()函数的用途是什么。

相关问题