【发布时间】:2011-03-24 16:42:31
【问题描述】:
您好,我目前正在进行项目的测试阶段(算法可视化工具)。我的 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 作为输入(尝试删除 10)或 5 和 12(尝试删除 12)但从不如果我使用例如 4 和 8(尝试删除 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;}
我真的需要这方面的帮助。如果需要,我可以发布整个课程。 谢谢!
【问题讨论】:
-
你能发布 NPE 的堆栈跟踪吗?
-
所以不涉及可视化?然后你应该改变你的帖子的标题,因为人们希望被问到一些可视化问题。
标签: java swing visualization binary-search-tree