[英]Binary Search Tree Visualisation In Java
嗨,我目前正在項目的測試階段(算法可視化工具)。 我的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)時,出現空指針異常,但是從不如果我使用例如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;}
我真的需要幫助。如有需要,我可以發布整個課程。謝謝!
只是一些注意事項:
if( check(current) == 0)
等->您應該檢查一次,然后執行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
為null並且current.right
為null,則current
之后將為null。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.