I am trying to remove a string from a BST and I cannot figure it out. I know how to remove integers but cannot convert my code to remove Nodes that have strings. Here is the code I currently have
/*
* Removes the specified string from the BST
*/
public boolean remove(String s){
Node ans = remove(root, s);
if(ans == null){
return false;
} else {
return true;
}
}
private static Node remove(Node root, String s) {
if (root == null)
return null;
if (s.compareTo(root.data) < 0) {
root.left = remove(root.left, s);
} else if (s.compareTo(root.data) > 0) {
root.right = remove(root.right, s);
} else {
if (root.left == null) {
return root.right;
} else if (root.right == null)
return root.left;
root.data = minimum(root.right);
root.right = remove(root.right, root.data);
}
return root;
}
public static String minimum(Node root) {
String minimum = root.data;
while (root.left != null) {
minimum = root.left.data;
root = root.left;
}
return minimum;
}
Replace all "Integer" with "String".
I know this was 2 years ago but I case someone needs help I did this instead..
private String minimum(BSTNode treeRoot) {
String minimum = treeRoot.value;
while (treeRoot.left != null) {
minimum = treeRoot.left.value;
treeRoot = treeRoot.left;
}
return minimum;
}
private BSTNode removeValue(BSTNode treeRoot, String s){
if(treeRoot == null){
return treeRoot;
} else if(s.compareTo(treeRoot.value) < 0){
treeRoot.left = removeValue(treeRoot.left, s);
} else if(s.compareTo(treeRoot.value) > 0){
treeRoot.right = removeValue(treeRoot.right, s);
} else {
if(treeRoot.left == null){
return treeRoot.right;
} else if(treeRoot.right == null){
return treeRoot.left;
}
treeRoot.value = minimum(treeRoot.right);
treeRoot.right = removeValue(treeRoot.right, treeRoot.value);
}
return treeRoot;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.