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