private E findStartingNodeForDeletion(E element) { if (root == null) return null; TreeNode<E> parent = null; TreeNode<E> current = root; while (current != null) { if (element.compareTo(current.element) < 0) { parent = current; current = current.left; } else if (element.compareTo(current.element) > 0) { parent = current; current = current.right; } else break; } if (current == null) return null; if (current.left == null) { if (parent == null) { return null; } else { return parent.element; } } else { TreeNode<E> parentOfRightMost = current; TreeNode<E> rightMost = current.left; while (rightMost.right != null) { parentOfRightMost = rightMost; rightMost = rightMost.right; } return parentOfRightMost.element; } }
public boolean delete(E element) { if (root == null) return false; TreeNode<E> parent = null; TreeNode<E> current = root; while (current != null) { if (element.compareTo(current.element) < 0) { parent = current; current = current.left; } else if (element.compareTo(current.element) > 0) { parent = current; current = current.right; } else break; } if (current == null) return false; if (current.left == null) { if (parent == null) { root = current.right; } else { if (element.compareTo(parent.element) < 0) parent.left = current.right; else parent.right = current.right; balancePath(parent.element); } } else { TreeNode<E> parentOfRightMost = current; TreeNode<E> rightMost = current.left; while (rightMost.right != null) { parentOfRightMost = rightMost; rightMost = rightMost.right; } current.element = rightMost.element; if (parentOfRightMost.right == rightMost) parentOfRightMost.right = rightMost.left; else parentOfRightMost.left = rightMost.left; balancePath(parentOfRightMost.element); } size--; return true; }