JAVA编写一个名为MyTree的泛型类,实现insert、remove和search三个泛型方法,用于存储任意类型的树形结构。请给出测试类和测试结果。
时间: 2024-05-15 16:18:55 浏览: 32
好的,我会按照要求回答您的问题。以下是您要求的Java代码,包括MyTree泛型类和相应的测试类:
```java
public class MyTree<T extends Comparable<T>> {
private Node<T> root;
private static class Node<T> {
T value;
Node<T> left;
Node<T> right;
Node(T value) {
this.value = value;
}
}
public void insert(T value) {
Node<T> node = new Node<>(value);
if (root == null) {
root = node;
} else {
insert(root, node);
}
}
private void insert(Node<T> parent, Node<T> node) {
if (node.value.compareTo(parent.value) < 0) {
if (parent.left == null) {
parent.left = node;
} else {
insert(parent.left, node);
}
} else {
if (parent.right == null) {
parent.right = node;
} else {
insert(parent.right, node);
}
}
}
public void remove(T value) {
root = remove(root, value);
}
private Node<T> remove(Node<T> node, T value) {
if (node == null) {
return null;
}
if (value.compareTo(node.value) < 0) {
node.left = remove(node.left, value);
return node;
} else if (value.compareTo(node.value) > 0) {
node.right = remove(node.right, value);
return node;
} else {
if (node.left == null && node.right == null) {
return null;
}
if (node.left == null) {
return node.right;
}
if (node.right == null) {
return node.left;
}
Node<T> tmp = findMin(node.right);
node.value = tmp.value;
node.right = remove(node.right, tmp.value);
return node;
}
}
private Node<T> findMin(Node<T> node) {
while (node.left != null) {
node = node.left;
}
return node;
}
public boolean search(T value) {
return search(root, value);
}
private boolean search(Node<T> node, T value) {
if (node == null) {
return false;
}
if (value.compareTo(node.value) < 0) {
return search(node.left, value);
} else if (value.compareTo(node.value) > 0) {
return search(node.right, value);
} else {
return true;
}
}
}
```
下面是测试使用的代码:
```java
public class TestMyTree {
public static void main(String[] args) {
MyTree<String> tree = new MyTree<>();
tree.insert("F");
tree.insert("D");
tree.insert("J");
tree.insert("B");
tree.insert("E");
tree.insert("G");
tree.insert("K");
tree.insert("A");
tree.insert("C");
tree.insert("I");
tree.insert("H");
System.out.println(tree.search("F")); // true
System.out.println(tree.search("Z")); // false
tree.remove("F");
System.out.println(tree.search("F")); // false
}
}
```
测试结果如下:
```
true
false
false
```
希望这个答案能够对您有所帮助!
阅读全文