1 回答
TA贡献1795条经验 获得超7个赞
Java 没有运算符重载。您不能将 Comparable 类型与>
. 你需要root.val.compareTo(newNode.val)
改用。
作为旁白:
Comparable 是一个接口,而不是一个类
你不需要指定
<P extends Comparable<P>>
将
addValHelper
代码移动到 Node 类本身可能更有意义它可能是有意义的
Node
实现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);
}
}
}
添加回答
举报