java - 在我的通用 BinaryTree 中找不到第一个/非附加值
问题描述
我试图创建我自己的 BinaryTree 类,我还得到了一个 JUnit-Class,它输出非附加值的测试和第一个附加值作为 Nullpointer..
Nullpointer 出现在我的 BinaryTree 类中的 while 循环中,这对我来说没有意义,因为我有以下代码行来检查它:
if(key.compareTo(current.key) == 0) {
return current.value;
}
return null;
}
应该首先检查第一个附加值(至少我认为)
这是我的代码:
public class BinaryTree<K extends Comparable<K>, V>{
int count = 0;
//Please don't add any further attributes.
private K key;
private V value;
private BinaryTree<K,V> left, right;
private BinaryTree<K,V> root;
/**
* Constructor creates new BinaryTree instance, initially without child nodes.
*/
// Done!!
public BinaryTree(K key, V value){
this.value = value;
this.key = key;
left = null;
right = null;
}
/**
* Stores a key-value pair in the tree.
* If the key has already been stored, then the current value for this key
* is replaced by the new value.
*/
public void put(K key, V value) {
BinaryTree<K,V> newNode = new BinaryTree<K,V>(key, value);
if (root == null) {
root = newNode;
root.value = value;
root.key = key;
count += 1;
return;
}
BinaryTree<K,V> current = root;
BinaryTree<K,V> parent;
while (true) {
parent = current;
if (key.compareTo(current.key) == -1) {
current = current.left;
if (current == null) {
parent.left = newNode;
count += 1;
return;
}
} else {
current = current.right;
if (current == null) {
parent.right = newNode;
count += 1;
return;
}
}
}
}
/**
* Returns the value object stored with the given key.
* Returns null if the key is unknown.
*/
public V get(K key) {
BinaryTree<K,V> current = root;
while(key.compareTo(current.key) != 0) {
if(key.compareTo(current.key) < 0) {
current = current.left;
} else if(key.compareTo(current.key) > 0) {
current = current.right;
}
}
if(key.compareTo(current.key) == 0) {
return current.value;
}
return null;
}
}
解决方案
推荐阅读
- c++ - SetWindowRgn 将窗口主题更改为 Classic
- c++ - 如何在给定位置反转 std::list?
- jquery - ASP.NET MVV Core 应用程序:加载资源失败:服务器响应状态为 404(未找到)bootstrap.css:1
- swagger - 我想从给定的 swagger.json 创建 curl 请求?
- sql - 将查询结果作为 CSV 文件从 Docker PostgreSQL 容器导出到本地机器
- mongodb-query - MongoDB 通配符索引 - 如何用索引覆盖投影
- c++ - 是否需要使用 Json::value object=Json::objectValue 来初始化?
- database - 使用实体框架的一对一关系
- reactjs - 定义和审查网络工作者
- javascript - 如何使用 axios 发送正文来调用这个 get api?