Я пытаюсь написать метод isEmpty для двоичного дерева, но у меня проблема. Так что это метод, который я использую.Метод isEmpty для двоичного дерева proble
public boolean isEmpty(){
if(root == null) return true;
else return false;
}
Когда я добавляю только один элемент, а затем удалить этот элемент, и вызвать IsEmpty, я не получаю верно, но неверно.
Есть ли что-то неправильно с моей реализацией?
Так что это способ удалить:
/**
* Internal method to remove from a subtree.
* @param x the item to remove.
* @param t the node that roots the tree.
* @return the new root.
* @throws ItemNotFoundException if x is not found.
*/
protected BinaryNode<AnyType> remove(AnyType x, BinaryNode<AnyType> t)
{
if(t == null)
throw new ItemNotFoundException(x.toString());
if(x.compareTo(t.element) < 0)
t.left = remove(x, t.left);
else if(x.compareTo(t.element) > 0)
t.right = remove(x, t.right);
else if(t.left != null && t.right != null) // Two children
{
t.element = findMin(t.right).element;
t.right = removeMin(t.right);
}
else
t = (t.left != null) ? t.left : t.right;
return t;
}
и это метод removeMin, который использует метод удалить:
/**
* Internal method to remove minimum item from a subtree.
* @param t the node that roots the tree.
* @return the new root.
* @throws ItemNotFoundException if t is empty.
*/
protected BinaryNode<AnyType> removeMin(BinaryNode<AnyType> t)
{
if(t == null)
throw new ItemNotFoundException();
else if(t.left != null)
{
t.left = removeMin(t.left);
return t;
}
else
return t.right;
}
Я думаю, проблема в функции удаления. Это выглядит нормально. – JProgrammer
Метод 'isEmpty' является правильным. Было бы здорово, если бы вы показали нам метод 'remove'. –
Это не причина вашей проблемы, но вы можете просто «вернуть root == null;» – Paul