您好我目前正在做我的項目(算法可視化工具)的測試階段。我遇到了我的BST刪除方法的問題。在Java中的二叉搜索樹可視化
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;}
我真的需要幫助this.I可以張貼全班如果需要的話.. 謝謝!
你可以發佈NPE的堆棧跟蹤嗎? – Thomas 2011-03-24 16:58:18
因此可視化不涉及?那麼你應該改變你發佈的標題,因爲人們期待一些可視化問題被問到。 – 2011-03-24 21:43:10