您好我正在进行项目的测试阶段(算法可视化工具)。我的BST删除方法出现问题。
public boolean delete(String key) {
boolean deleted = true;
boolean finished=false;
BNode current = root;
BNode prev = null;
while (!finished) {
if (key.compareTo(current.key) > 0) {
prev = current;
current = current.right;
this.repaint();
}
else if (key.compareTo(current.key) < 0) {
prev = current;
current = current.left;
this.repaint();
}
else if (key.compareTo(current.key) == 0) {
finished=true;
this.repaint();
}
}
if (check(current) == 0) {
if(current==root)
{
root=null;
xPos=400;
yPos=60;
this.repaint();
}
else
{
if (current.key.compareTo(prev.key) > 0) {
prev.right = null;
this.repaint();
}
else if(current.key.compareTo(prev.key) < 0) {
prev.left = null;
this.repaint();
}
}
}
else if (check(current) == 1) {
if(current==root)
{
prev=current;
if (current.left != null) {
current=current.left;
prev.key=current.key;
prev.left = current.left;
this.repaint();
}
else {
current=current.right;
prev.key=current.key;
prev.right = current.right;
this.repaint();
}
}
else
{
if (current.key.compareTo(prev.key) > 0) {
if (current.left != null) {
prev.right = current.left;
this.repaint();
}
else {
prev.right = current.right;
this.repaint();
}
}
else if(current.key.compareTo(prev.key) < 0) {
if (current.left != null) {
prev.left = current.left;
this.repaint();
}
else {
prev.left = current.right;
this.repaint();
}
}
}
}
else if (check(current) == 2) {
BNode temp = inord(current);
if(current==root)
{
root.key=temp.key;
this.repaint();
}
else
{
if (current.key.compareTo(prev.key) > 0) {
prev.right.key = temp.key;
this.repaint();
}
else {
prev.left.key = temp.key;
this.repaint(0);
}
}
}
return deleted;}
BST类本身的代码要长得多。一切正常,但是当我尝试删除没有子节点的节点时,当我使用例如9和10作为输入(尝试del 10)或5和12(尝试del 12)时,我得到一个nullpointer异常但是从不如果我使用例如4和8(尝试del 8)或9,6和5.我认为问题在于compareTo。
int check(BNode a) {
int ret;
if ( (a.left != null) && (a.right != null)) {
ret = 2;
}
else if ( (a.left == null) && (a.right == null)) {
ret = 0;
}
else {
ret = 1;
}
return ret;}
我真的需要帮助。如果需要,我可以发布全班。 谢谢!
答案 0 :(得分:0)
只是几点说明:
if( check(current) == 0)
等 - &gt;你应该检查一次,然后执行if(甚至是一个开关)2。的例子:
int result = check(current);
switch(result) {
case 0:
//do whatever is appropriate
break;
case 1:
//do whatever is appropriate
break;
case 2:
//do whatever is appropriate
break;
default:
//should never happen, either leave it or throw an exception if it ever happens
}
编辑://实际上,忘了这个编辑,只是看到这不应该发生,但它仍然不是一个好的风格
您的代码中也有类似的内容:
if (current.left != null) {
current=current.left;
prev.key=current.key;
prev.left = current.left;
this.repaint();
}
else {
current=current.right; //this might be null
...
}
如果current.left
为空且current.right
为空,则current
之后将为空。