gpt4 book ai didi

java - 二叉搜索树中的节点删除

转载 作者:行者123 更新时间:2023-12-01 15:02:24 26 4
gpt4 key购买 nike

我正在尝试从存储单词(如字典)的二叉搜索树中删除一个节点。 DictEntry 元素包含单词、定义和将显示的定义类型的数字(字符串、图像等)。当未找到该单词时,将引发 DictionaryException。

用户必须能够仅通过在方法中输入单词来删除条目。这些是用于删除的以下方法;

public void remove(String word) throws DictionaryException {
if (root!=null) {
//checks if the word is equal to the entrie's word
if (word.equals(root.getElement().word()))
root = replacement(root);
else {
// parent is the node above current
BinaryTreeNode<DictEntry> current, parent = root;
boolean found = false;
// if lexicographically smaller than the root's word
if (word.compareTo(root.getElement().word()) < 0)
current = root.getLeft();
// if lexicographically higher than the root's word
else
current = root.getRight();
while (current != null && !found) {
if (word.equals(current.getElement().word())) {
found = true;
if (current == current.getLeft())
parent.setLeft(replacement(current));
else
parent.setRight(replacement(current));
} else {
parent = current;

if (word.compareToIgnoreCase(current.getElement()
.word()) < 0)
current = current.getLeft();
else
current = current.getRight();
}// end if else
}// end while
if (!found)
throw new DictionaryException("The entry was not found");
}
}
}

private BinaryTreeNode<DictEntry> replacement(BinaryTreeNode<DictEntry> node) {
BinaryTreeNode<DictEntry> found = null;
// check if both sides are empty
if (node.getLeft() == null && node.getRight() == null)
found = null;
else if (node.getLeft() != null && node.getRight() == null)
found = node.getLeft();
else if (node.getLeft() == null && node.getRight() != null)
found = node.getRight();
// if both sides have an entry
else {
//helper positions
BinaryTreeNode<DictEntry> current = node.getRight();
BinaryTreeNode<DictEntry> parent = node;

//moving positions
while (current.getLeft() != null) {
parent = current;
current = current.getLeft();
}// end while

if (node.getRight() == current)
current.setLeft(node.getLeft());
else {
parent.setLeft(current.getRight());
current.setRight(node.getRight());
current.setLeft(node.getLeft());
}
found = current;
}// end if else
return found;
}

我的问题是,每当我尝试像这样测试它时,节点都不会被删除,其中字典代表 BinarySearchTree;

// Insert and remove a word
try {
dictionary.insert("course","A series of talks or lessons",1);
dictionary.remove("course");
res = dictionary.findWord("course");
if (res == "") {System.out.println("Remove test passed");}
else {System.out.println("Remove test failed");}
}
catch(DictionaryException e) {
System.out.println("Remove test 4 failed");
}

我尝试查看并使用我的插入方法,但我什么也没得到,所以我假设问题出在我的删除逻辑中的某个地方。

最佳答案

从初步看来,替换方法是使用 == 运算符进行 Node 比较。这只比较节​​点的内存地址。如果您想根据节点的值进行比较,则需要使用 .equals() 方法。

关于java - 二叉搜索树中的节点删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13450957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com