【发布时间】:2021-01-15 13:18:41
【问题描述】:
public void insert(String word,String def){
Node newNode = new Node(word, def);
if(root==null){
root=newNode;
}
Node p, q ;
p = q = root ;
while (q != null){
p = q ;
int c = word.compareToIgnoreCase(p.getWord());
if (c < 0) {
q = p.getLeft() ;
}
else{
q = p.getRight() ;
}
}
int c = word.compareToIgnoreCase(p.getWord());
if (c < 0) {
p.setLeft(newNode);
}
else{
p.setRight(newNode);
}
}
我编写这段代码是为了在二叉搜索树中插入节点,但它没有按计划工作。
无限运行后进入根和根后一个节点。 我找不到任何解决方案。
【问题讨论】:
-
如果您想在树为空时将新节点作为根插入,我认为您在
if(root==null)中缺少return语句。 -
不一定是解决方案,但您不应该从
if (root == null)返回或将方法的其余部分放在else块中吗? -
@Slaw yk 你已经解决了问题
-
@Slaw idk 为什么我一开始没有想到这个。非常感谢。
标签: java data-structures tree binary-tree binary-search-tree