我正在尝试在java中实现二叉树,这是我的代码:
class TestClass {
public static void newnode(int a , Node root,){
root = new Node(a);
System.out.println(root.data); // Printing out 22
}
public static void main(String args[] ) throws IOException {
Node root = null;
newnode(22,root);
System.out.println(root.data); // Giving NullPointerException
}
}
class Node{
Node left ;
Node Right;
int data ;
Node(int dataa){
this.data = dataa;
}
}
我无法在树中插入新节点,根的值不会改变
当我调用 newnode 函数时,我得到了根节点的正确值,但在主函数中它给出了我的空点异常
为什么root的值没有更新
最佳答案
class TestClass {
public static Node newnode(int a , Node root){
root = new Node(a);
System.out.println(root.data); // Printing out 22
return root;
}
public static void main(String args[] ) throws IOException {
Node root = null;
root = newnode(22,root);
System.out.println(root.data); // Giving NullPointerException
}
}
试试这个
关于java - 二叉树的java实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27498915/