Skip to content

Instantly share code, notes, and snippets.

@gtke
Created January 28, 2013 19:42
Show Gist options
  • Select an option

  • Save gtke/4658396 to your computer and use it in GitHub Desktop.

Select an option

Save gtke/4658396 to your computer and use it in GitHub Desktop.
BST Deletion
/**
* Removes a data entry from the BST
*
* null is positive infinity
*
* @param data The data entry to be removed
* @return The removed data entry (null if nothing is removed)
*
*/
public T remove(T data) {
boolean b = false;
if(contains(data)){
b = true;
}
root = remove(root, data);
if(b){
return data;
}
return null;
}
private Node<T> remove(Node<T> here, T data) {
if (here != null) {
if(data == null){
here.right = remove(here.right, data);
if(here.getData() == null){
here = removeNode(here);
}
}else{
if (data.compareTo(here.getData()) < 0) {
here.left = remove(here.left, data);
} else if (data.compareTo(here.getData()) > 0) {
here.right = remove(here.right, data);
} else {
here = removeNode(here);
}
}
}
return here;
}
private Node<T> removeNode(Node<T> here) {
if (here.left == null)
here = here.right;
else if (here.right == null)
here = here.left;
else {
Node<T> big = here.left;
Node<T> last = null;
while (big.right != null) {
last = big;
big = big.right;
}
here.data = big.data;
if (last == null) {
here.left = big.left;
} else {
last.right = big.left;
}
}
return here;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment