Created
January 28, 2013 19:42
-
-
Save gtke/4658396 to your computer and use it in GitHub Desktop.
BST Deletion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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