[英]how to add nodes in binary search tree properly?
这是我的代码
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;
}
希望它会对你有所帮助。
正如Aaron指出的那样,您需要更新下一个要比较的新密钥。 在您的代码中,如果左侧节点为null,则插入节点,但如果它不为null,则需要将密钥与此新节点的密钥进行比较。 这段代码在哪里?
else if(key.compareTo(subroot.key) < 0){
if(subroot.left != null){
subroot = root.left;
// WHERE ARE YOU USING KEY OF THIS NEW NODE subroot FOR COMPARISON?
return insertWord(key, meaning);
}
else{
subroot.left = new TreeNode();
subroot.left.key = key;
subroot.left.meaning = meaning;
}
}
编辑:左右插入方法的实现应该是类似的:
private void insertNodeToLeft(Node<T> parent, Node<T> child) {
// New left node
parent.setLeft(child);
child.setParent(parent);
size++;
}
private void insertNodeToRight(Node<T> parent, Node<T> child) {
// New right node
parent.setRight(child);
child.setParent(parent);
size++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.