为什么这个深度优先搜索会产生NullPointerException?

use*_*710 1 java binary-tree nullpointerexception

我有一小段代码来生成任意二叉搜索树的深度优先搜索.这是我的代码:

public void printByDepth()
{
    Queue<BinaryNode<T>> queue = new LinkedList<BinaryNode<T>>();
    BinaryNode<T> current = this;
    queue.add(current);
    while(!queue.isEmpty()){
        current = queue.remove();
        System.out.println(current.element);
        if(current.left != null)
            queue.add(current.left);
        if(current.right != null) // had an extra semicolon here, fixed
            queue.add(current.right);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一种非常标准的队列方法,但由于某种原因,第8行(println(current.element))产生了一个NPE.我正在使用的树应该产生以下DF输出:F B G A D I C E H.我已经在纸上完成了这一点,在遍历整个树之前我永远不会得到current = null或queue.isEmpty()= true(至少在这种情况下),所以我不确定为什么会发生这种情况.没有节点具有空内容.

另外,有趣的是,如果我将while条件更改为while(current != null)我没有获得NPE但输出为:F B G A D I,则缺少最后一级的元素.

我确定有一些简单的我想念......有什么提示吗?

编辑:失控分号=(谢谢,罗杰.

Rog*_*sjö 6

问题在于:

if(current.right != null);
        queue.add(current.right);
Run Code Online (Sandbox Code Playgroud)

在if上看到你的分号(;)?这基本上意味着:如果current.right不为null,则不执行任何操作.之后,始终将current.right添加到队列中(即使为null).

如果您自动格式化代码,这将更容易看到,因为您的缩进现在错误地建议添加current.right属于if语句.