在java中使用字符串作为BST键
我有一个存储对象的二进制搜索树。我可以使用字符串值作为键,它只存储第一个键,也只搜索第一个值,所有其他键find返回null 第一个值是 这是我的密码:救命在java中使用字符串作为BST键,java,binary-search-tree,Java,Binary Search Tree,我有一个存储对象的二进制搜索树。我可以使用字符串值作为键,它只存储第一个键,也只搜索第一个值,所有其他键find返回null 第一个值是 这是我的密码:救命 public void addNode(String key, String name) { // Create a new Node and initialize it Node newNode = new Node(key, name); // If there is no root this becomes
public void addNode(String key, String name) {
// Create a new Node and initialize it
Node newNode = new Node(key, name);
// If there is no root this becomes root
if (root == null) {
root = newNode;
} else {
// Set root as the Node we will start
// with as we traverse the tree
Node focusNode = root;
// Future parent for our new Node
Node parent;
while (true) {
parent = focusNode;
if (key.compareTo(focusNode.name) <= 0) {
// Switch focus to the left child
focusNode = focusNode.leftChild;
// If the left child has no children
if (focusNode == null) {
// then place the new node on the left of it
parent.leftChild = newNode;
return; // All Done
}
} else if(key.compareTo(focusNode.name) >= 0){ // If we get here put the node on the right
focusNode = focusNode.rightChild;
// If the right child has no children
if (focusNode == null) {
// then place the new node on the right of it
parent.rightChild = newNode;
return; // All Done
}
}
}
}
}
据我所见,您的问题是,在您的案例中,您正在将键与值name进行比较。例如,而不是:
if (key.compareTo(focusNode.name) <= 0) {...
尝试:
另外,另一个问题是,您从未处理两个键相等的情况,而是继续处理左边的子项。此时,您可能还想做一些其他的事情,我猜应该是更新名称并从方法返回
if (key.compareTo(focusNode.key) <= 0) {...