now i'm try to make the delete and successor method for BST in java
public void delete(BinarySearchTree<V> pointer) {
// 1. The node is a leaf.
// 2. The node has no left child.
// 3. The node has no right child.
// 4. The node has two children.
BinarySearchTree<V> current = root;
BinarySearchTree<V> parent = root;
while(pointer.getData().compareTo(current.getData()) != 0){
parent = current;
if(pointer.getData().compareTo(current.getData()) >0){
current= current.getLeft();
}
else{
current = current.getRight();
}
if(current == null)
return;
}
// test for a leaf
if(current.getLeft() == null && current.getRight() == null)
{
if(current == root) //tree has a single node, make root null
parent = null;
else if(current.getLeft() == current.getLeft()) //current is a left child so make its parent's left null
parent = null;
// test for no right child
else if(current.getRight() == null)
if(current == root) //current is root so make root point to current's left
root = current.getLeft(); //old root gets deleted by garbage collector
else if(current.getLeft() == current.getLeft()) //current is a left child so make its parent's left point to it's left child
parent = current.getLeft();
else //current is a right child so make its parent's right point to it's left child
parent.getRight() = current.getLeft();
// test for no left child
else if(current.getLeft() == null)
if(current == root) //current is root so make root point to current's right
root = current.getRight(); //old root gets deleted by garbage collector
else if(current.getLeft() == current.getLeft()) //current is a left child so make its parent's left point to it's right child
parent.getLeft() = current.getRight();
else //current is a right child so make its parent's right point to it's right child
parent.getRight() = current.getRight();
}
}
and this one is
@Override
public BinarySearchTree<V> next(BinarySearchTree<V> pointer) {
BinarySearchTree<V> successorParent = pointer;
BinarySearchTree<V> successor = pointer;
BinarySearchTree<V> current = pointer.getRight();
while(current != null)
{
successorParent = successor;
successor = current;
current = current.getLeft();
}
if(successor != pointer.getRight())
{
successorParent.getLeft() = successor.getRight();
successor.getRight() = pointer.getRight();
}
return successor;
}
i got the code from the internet and seems like it doesn't to me it still has some errors when i try to call parent.getLeft() or .getRight()
but when i use current.getLeft() or .getRight() it works
As you can see the code i already declared both of them
" BinarySearchTree<V> current = root;"
" BinarySearchTree<V> parent = root;"
can you plz help me fix the code or guide me the delete method