Implementing Delete
Last class, we finsihed up by discussing the algorithm for deleting a node within a BST. Today, we walked through the implementation together:
public void delete (Comparable c) { root = delete(root, c); } /* * A recursive method that will copy the correct data into the node to * be deleted, and then call delete on the node where it got that data. * The method will continue to go recursively, until it is called to delete * a leaf, in which case it merely makes the reference to that node null. */ private static BinaryNode delete (BinaryNode bn, Comparable c) { if (null == data) return root; if (null == root) return null; if (data.compareTo(root.getData()) == 0) { if (root.isLeaf()) return null; if (root.getLeft() == null) return root.getRight(); if (root.getRight() == null) return root.getLeft(); Comparable replacementData = getRightmost(root.getLeft()); return new BinaryNode (/* data */ replacementData, /* left */ delete(root.getLeft(), replacementData), /* right */ root.getRight()); } else if (data.compareTo(root.getData()) < 0) { root.setLeft(delete(root.getLeft(), data)); return root; } else { root.setRight(delete(root.getRight(), data)); return root; } } /* * The method to find the rightmost node in the left subtree. * It is used to find the proper data to put in the node to be deleted. */ private BinaryNode getRightmost(BinaryNode bn) { // Special case: empty tree if (null == bn) return null; // Special case: no right child if (null == bn.getRight()) return bn; // Common case: Go right return getRightmost(bn.getRight()); }