java - 使用 While 循环搜索二叉树

标签 java binary-tree binary-search-tree

我正在尝试编写一个在我构建的树上搜索值的函数,我已经编写了一个工作正常的递归函数。现在我想提高我的运行时间,所以我想使用 while 循环来查找值。问题是我收到了 NullPointerException。我确信这棵树没问题,因为在执行搜索之前我打印了所有值。那么我的代码有什么问题呢?

public void SearchByLoop(Node root,final int val){

        while(root != null || root.getVal() == val){

            if(root.getVal() < val)

                root = root.getRightChild();

            else if(root.getVal() > val)

                root = root.getLeftChild();

        }

        if(root == null)

            System.out.println("Couldn't find value " + val);

        else if(root.getVal() == val)

                System.out.println("Found value " + val);

    }

public class Main {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Tree theTree = new Tree();
    Random rand = new Random();//Create random variable.
    int val = 0; 
    for(int i = 0 ; i < 100; i ++){

        val = rand.nextInt(151) + (0);
        theTree.addNode(val,"a");
    }
    theTree.inOrderTraverseTree(theTree.getRoot());
    theTree.SearchByLoop(theTree.getRoot(), 10);

}
}

现在,inOrderTraverse 方法会打印所有值,所以我知道树没问题。可能是什么问题?谢谢!

最佳答案

这个条件

while(root != null || root.getVal() == val)

root为空时,会给你一个NullPointerException。

你可能想要

while(root != null && root.getVal() != val)

关于java - 使用 While 循环搜索二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36841350/

相关文章:

java - 如何在文本中定义人名(Java)

data-structures - 使用数组表示的二叉树

c# - 表达式评估 - 避免 StackOverflow 异常

c++ - 计算树中的所有节点

algorithm - 二叉搜索树是否可以仅由中序遍历构建?

C++ 二叉搜索树和指针

java - 仅当键存在时才向 ArrayList 添加数据

java - java中的ThreadGroup相对于创建单独的线程有什么好处?

java - 使用 maven-surefire 运行测试时,Spring-Autowiring 发生在 @BeforeClass 之后

java - 无法使用 TreeSet 的 contains() 方法