Java:如何实现通用二进制搜索树? [英] Java : How do I implement a generic Binary Search Tree?
本文介绍了Java:如何实现通用二进制搜索树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
到目前为止,我一直在编写Node类
Until now, I have been writing a Node class as
class Node {
private value;
private Node left;
private Node right;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
}
和二进制搜索树为
public class BinarySearchTree {
private Node root;
public BinarySearchTree(int value) {
root = new Node(value);
}
public void insert(int value) {
Node node = new Node(value);
// insert logic goes here to search and insert
}
}
现在我想支持BinarySearchTree有任何类型的插入节点,如字符串,人
Now I would like to support BinarySearchTree to have insert node of any type like strings, people
如何使其保持通用以保存任何类型?
How can I make it generic to hold any type?
推荐答案
使用泛型:
class Node<T extends Comparable<T>> {
private T value;
...
}
public class BinarySearchTree<T extends Comparable<T>> {
private Node<T> root;
public BinarySearchTree(T value) {
root = new Node<T>(value);
}
public void insert(T value) {
Node<T> node = new Node<T>(value);
// insert logic goes here to search and insert
}
}
这篇关于Java:如何实现通用二进制搜索树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文