我想在泛型中實現一個二叉樹,我搜索了,我發現這個問題:Implementing Binary Tree in Java with Generic Comparable<T> data?,但我無法解決我的疑惑。所以,我有兩個班,在二叉樹中的Java泛型,不兼容的類型錯誤
BST_Tree<T>
和
Node<T extends Comparable<T>>
32,我想實現可以:
採取每一種類型的對象,並把它的領域
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節點的關鍵,但它失敗。這是錯誤:
incompatible types: T cannot be converted to java.lang.Comparable
先謝謝您!
'BST_Tree' ='BinarySearchTree_Tree' – Clashsoft
爲獲得最佳效果,請使用'>' –
newacct
我可以問你爲什麼?感謝您的方式 – Francesco