[英]JAVA BST return node instance of BST node?
我正在做一個 BST 項目,它在 BST 中搜索一個值,如果找到則返回。 我使用了一種測試方法來檢查代碼,它工作正常。 問題來自我猜的返回類型。
public BSTNode contains(BSTNode root, String needle) {
BSTNode current = root;
while (current != null) {
if (current.getData().compareTo(needle) > 0)
current=current.getLeft();
else if (current.getData().compareTo(needle) < 0)
current=current.getRight();
else if (current.getData().compareTo(needle) == 0)
return current;
else current=null;
}
return current;
}
結果:
BSTNode node = bst.contains(root, "delta");
Assertions.assertTrue(node instanceof BSTNode);
錯誤的;
BSTNode node = bst.contains(root, "delta");
Assertions.assertTrue(true);
真的;
據我了解,我相信代碼可以正常工作並且返回值是正確的。 我只是不明白“BSTNode 的節點實例”為什么它是錯誤的,我該如何解決?
謝謝先進
如您所寫,您的方法只能返回 null。 僅當current
為null
時退出while
循環,然后返回current
。 null instanceof Anything
總是假的。
線路current=current;
如果找到該值也會導致無限循環。
這兩個都可以同時解決:當比較為 0 時,您應該返回current
。
由於您已經知道您實際上錯了,所以我通過修改您現有的代碼來添加一個約束。
在 BST 的情況下,將有 3 點:
因此,除非您找到要查找的密鑰或遍歷所有可能的密鑰,否則您需要迭代。 無論哪種情況,您都需要停止迭代。
public BSTNode contains(BSTNode root, String needle) {
BSTNode current = root;
/* the variable you will return at the end */
BSTNode result = null;
/* iterate the loop until current becomes null or result becomes not null */
while (current != null && result == null) {
/* when you found what you were looking for */
if (current.getData().compareTo(needle) == 0){
result = current;
}else if (current.getData().compareTo(needle) > 0){
current=current.getLeft();
}else{
current=current.getRight();
}
}
/* return the result at the end, it will be either null or the value you were looking */
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.