java-如何在二进制搜索树中正确添加节点?
作者:互联网
这是我的代码
public boolean insertWord(String key, String meaning) {
if((root == null) ){
root = new TreeNode();
root.key = key;
root.meaning = meaning;
}
else{
TreeNode subroot = root;
if(subroot.key.compareTo(key) == 0){
return false;
}
else if(key.compareTo(subroot.key) < 0){
if(subroot.left != null){
subroot = root.left;
return insertWord(key, meaning);
}
else{
subroot.left = new TreeNode();
subroot.left.key = key;
subroot.left.meaning = meaning;
}
}
else{
if(subroot.right != null){
subroot = root.right;
return insertWord(key, meaning);
}
else{
subroot.right = new TreeNode();
subroot.right.key = key;
subroot.right.meaning = meaning;
}
}
}
return true;
}
这样做给了我stackoverflow错误.有人可以帮我了解为什么我继续收到该错误.我知道它是由于无限循环引起的,但我不知道它为什么会发生.有人可以告诉我它在哪里发生以及如何解决吗?谢谢
解决方法:
在下面的代码中,如果subroot设置为root.left,那么您是否应该进一步使用subroot的密钥?您在哪里传递这些信息?
if(subroot.left != null){
subroot = root.left;
return insertWord(key, meaning);
}
现在,我将介绍已实现的版本:
protected Node<T> insertValue(T value) {
Node<T> newNode = getNewNode(value);
// If root is null, assign
if (root == null) {
root = newNode;
size++;
return newNode;
}
Node<T> currentNode = root;
while (currentNode != null) {
if (newNode.getData().compareTo(currentNode.getData()) <= 0) { // Less than or equal to goes left
if(currentNode.getLeft() == null) {
insertNodeToLeft(currentNode, newNode);
break;
}
currentNode = currentNode.getLeft();
} else { // Greater than goes right
if (currentNode.getRight() == null) {
insertNodeToRight(currentNode, newNode);
break;
}
currentNode = currentNode.getRight();
}
}
return newNode;
}
希望对您有帮助.
标签:binary-tree,binary-search-tree,java 来源: https://codeday.me/bug/20191120/2043589.html