I like that the delete method can remove the node and replace it with the minimum value of the right subtree. I do not want the setSrting method so I need to make a mistake when I replace the value (minimum right subtree). I tried to insert("b"), insert("d"), insert("c"), insert("a")and delete("b"). it removes "c"instead "b", I really don't understand why it works this way. Please help me fix the Delete method error. Thanks.
class StringNode {
private String word;
private StringNode left, right;
public StringNode(String w) {
word = w;
left = right = null;
}
public StringNode getLeft() {
return left;
}
public void setLeft(StringNode pt) {
left = pt;
}
public StringNode getRight() {
return right;
}
public void setRight(StringNode pt) {
right = pt;
}
public String getString() {
return word;
}
}
class BSTStrings {
private StringNode root;
public BSTStrings() {
root = null;
}
public String toString() {
return toString(root, 0);
}
private static String toString(StringNode l, int x) {
String s = "";
if (l == null)
;
else {
if (l.getLeft() != null)
s = '(' + toString(l.getLeft(), x + 1) + ')';
s = s + l.getString() + "-" + x;
if (l.getRight() != null)
s = s + '(' + toString(l.getRight(), x + 1) + ')';
}
return s;
}
public StringNode search(String s) {
return search(root, s);
}
private StringNode search(StringNode x, String s) {
int cmp = s.compareTo(x.getString());
if (cmp == 0)
return x;
else if (cmp < 0)
return search(x.getLeft(), s);
else
return search(x.getRight(), s);
}
public void insert(String s) {
if (s == null)
;
root = insert(root, s);
}
private StringNode insert(StringNode x, String s) {
if (x == null) {
x = new StringNode(s);
}
int cmp = s.compareTo(x.getString());
if (cmp < 0)
x.setLeft(insert(x.getLeft(), s));
else if (cmp == 0)
;
else
x.setRight(insert(x.getRight(), s));
return x;
}
public void delete(String val) {
if (val == null)
;
delete(root, val);
}
private StringNode delete(StringNode x, String val) {
int cmp = val.compareTo(x.getString());
if (x == null)
;
else if (cmp < 0)
x.setLeft(delete(x.getLeft(), val));
else if (cmp > 0)
x.setRight(delete(x.getRight(), val));
else {
if (x.getLeft() == null)
return x.getRight();
if (x.getRight() == null)
return x.getLeft();
StringNode t = x;
x = min(t.getRight());
x.setRight(deleteMin(t.getRight()));
x.setLeft(t.getLeft());
}
return x;
}
private StringNode deleteMin(StringNode x) {
if (x.getLeft() == null)
return x.getRight();
x.setLeft(deleteMin(x.getLeft()));
return x;
}
private StringNode min(StringNode x) {
if (x.getLeft() == null)
return x;
else
return min(x.getLeft());
}
public int height() {
return height(root);
}
private int height(StringNode x) {
if (x == null)
return -1;
return 1 + Math.max(height(x.getLeft()), height(x.getRight()));
}
}
source
share