Визуализация бинарного дерева поиска в Java - PullRequest
1 голос
/ 24 марта 2011

Привет, я сейчас на стадии тестирования моего проекта (Algorithm Visualization Tool).У меня проблема с методом удаления моего 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 намного длиннее.Все работает нормально, за исключением того, что, когда я пытаюсь удалить узел без дочернего элемента, я получаю исключение nullpointer, когда я использую, например, 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;}

Мне действительно нужна помощь с этим. Я могу опубликовать веськласс, если нужно .. Спасибо!

1 Ответ

0 голосов
/ 24 марта 2011

Всего несколько заметок:

  1. Если вы пройдете null для проверки, вы получите NPE.
  2. 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
}

Edit: // На самом деле, забудьте об этом редактировании, просто увидели, что этого не должно происходить,но это все еще не очень хороший стиль

В вашем коде также есть такие вещи:

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 будетпотом ноль.

...