【发布时间】:2015-10-17 14:32:06
【问题描述】:
我正在尝试使用泛型在 java 中实现二叉树,我搜索并找到了这个问题:Implementing Binary Tree in Java with Generic Comparable<T> data?,但我无法解决我的疑问。所以我有两个班,
BST_Tree<T>
和
Node<T extends Comparable<T>>
我希望我的实现可以:
将每种类型的Object放入Node中的
key字段中将每个节点与
key字段进行比较
这是代码:
public class Node < T extends Comparable < T >> {
private T key;
private Node left;
private Node right;
private Node p;
public void setKey(T key) {
this.key = key;
}
public T getKey() {
return key;
}
public Node getLeft() {
return left;
}
public Node getRight() {
return right;
}
public void setLeft(Node left) {
this.left = left;
}
public void setRight(Node right) {
this.right = right;
}
public void setP(Node p) {
this.p = p;
}
public boolean getBolCompMin(T key) {
return this.key.compareTo(key) < 0;
}
}
我的 Node 类应该扩展 Comparable 以便比较密钥。
这是我的树:
public class BST_Tree < T > {
private ArrayList < Node > nodes;
private Node root;
public BST_Tree(Node root) {
this.root = root;
}
public void insertNode(T key) {
Node z = new Node();
z.setKey(key);
Node x = this.root;
Node y = new Node();
while (x != null) {
y = x;
if (z.getBolCompMin(x.getKey())) {
x = x.getLeft();
} else {
x = x.getRight();
}
}
z.setP(y);
if (z.getBolCompMin(y.getKey())) {
y.setLeft(z);
} else {
y.setRight(z);
}
}
public void InOderWalk(Node x) {
if (x != null) {
InOderWalk(x.getLeft());
System.out.println(x.getKey());
InOderWalk(x.getRight());
}
}
public Node getRoot() {
return root;
}
}
我的树尝试在节点 z 中设置键,但失败了。这是错误:
不兼容的类型:T 无法转换为 java.lang.Comparable
提前谢谢你!
【问题讨论】:
-
BST_Tree=BinarySearchTree_Tree -
为了获得最佳效果,请使用
<T extends Comparable<? super T>> -
我能问你为什么吗?顺便谢谢你