1 回答

TA貢獻1795條經(jīng)驗 獲得超7個贊
Java 沒有運算符重載。您不能將 Comparable 類型與>
. 你需要root.val.compareTo(newNode.val)
改用。
作為旁白:
Comparable 是一個接口,而不是一個類
你不需要指定
<P extends Comparable<P>>
將
addValHelper
代碼移動到 Node 類本身可能更有意義它可能是有意義的
Node
實現(xiàn)Comparable
。
這樣,您的代碼感覺更加地道,并且您不會將 Node 的字段暴露給 BST。
public class BST<T implements Comparable<T>> {
private final Node<T> root;
/** Presumably this is run when a value is added.. */
private void addValueHelper(Node rootNode, Node newNode) {
rootNode.attachChild(newNode);
}
public static class Node implements Comparable<T> {
private final T val;
private Node left;
private Node right;
public Node(T val) {
this.val = val;
}
public int compareTo(Node other) {
return this.val.compareTo(other.val);
}
/**
* Takes the given node and compares it with the current node.
* If the current node is greater than the given node, the given node is placed to the left.
* Otherwise it is placed to the right.
*/
protected void attachChild(Node newNode) {
if (this.compareTo(newNode) == 1) {
if (this.left == null) {
this.left = newNode;
return;
}
this.left.attachChild(newNode);
return;
}
if (this.right == null) {
this.right = newNode;
return;
}
this.right.attachChild(newNode);
}
}
}
添加回答
舉報