使用 While 循环搜索二叉树

Searching Binary Tree with a While loop

我正在尝试编写一个函数来搜索我构建的树上的值,我编写了一个工作正常的递归函数。现在我想改善我的 运行 时间,所以我想使用 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 为 null 时,

会给你一个 NullPointerException。

你可能想要

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