【发布时间】:2018-03-25 19:42:00
【问题描述】:
我正在尝试编写一种递归方式来使用 java 插入到我的二叉搜索树中,但它无法正常工作并给出空指针异常 我的 node.java 代码是
public class Node
{
public int data;
public Node left;
public Node right;
public Node()
{
this.data = -1;
this.left = null;
this.right = null;
}
public Node(int n)
{
this.data = n;
this.left = null;
this.right = null;
}
}
我在 Tree.java 中的代码是
public class Tree
{
public Node head = new Node();
public void insert(int n , Node m)
{
if(m == null || m.data == -1)
{
m = new Node(n);
}
else
{
if(m.data > n)
{
insert(n,m.left);
}
else if(m.data < n)
{
insert(n,m.right);
}
}
}
public void print()
{
System.out.println(head.data);
System.out.println(head.left.data);
System.out.println(head.right.data);
}
}
而test.java代码是
public class Test
{
public static void main(String[] args)
{
Tree t = new Tree();
Node m = new Node();
t.insert(12,t.head);
t.insert(11,t.head);
t.insert(13,t.head);
t.print();
}
}
当我编译并运行时,它给出了以下错误
-1
Exception in thread "main" java.lang.NullPointerException
at Tree.print(Tree.java:28)
at Test.main(Test.java:10)
【问题讨论】:
-
您永远不会将子节点添加到树中的
head节点。你的插入方法没有意义 -
我递归调用它们,所以在第二步或第三步 m.left 或 m.right 不是节点,但我在堆栈跟踪中创建了它们,所以我认为不需要添加
标签: java recursion data-structures binary-search-tree