Bryan:
- Esto no es todo el código contenido dentro de la clase, pero si esto no es suficiente Voy a añadir el resto también.
- añadir () está destinado a añadir el valor a la posición correcta en la BST con la tecla. Si la clave ya existe, no hacer nada.
contains () se supone que devolver True si la clave está en el árbol
```public class Node { public Node left; public Node right; public int key; public String value; public void add ( int key, String value ) { if ( key.compareTo ( this.key ) < 0) { if ( left != null ) left.add ( key, value ) else left = new Node ( key, value ); } else if ( key.compareTo ( this.key ) > 0 ) { if ( right != null ) right.add ( key, value ); else right = new Node ( key, value); } else this.value = value; } public boolean contains ( int key ) { if ( this.key == ( key ) ) return value; if ( key.compareTo ( this.key ) < 0 ) return left == null ? null : left.contains ( key ); else return right == null ? null : right.contains ( key ); } }
Jason:
La cuestión es que int
es primitiva y por lo tanto no implementa Comparable por lo que no puede utilizar int.compareTo, sin embargo la variación en caja Entero hace. Usted puede simplemente utilizar enteros en lugar de int, o alternativamente usar Integer.compare (1, 2) y conservar su uso de primitivas.
public static class Node {
public Node left;
public Node right;
public Integer key;
public String value;
public Node(Integer key, String value) {
this.key = key;
this.value = value;
}
public void add(Integer key, String value) {
if (key.compareTo(this.key) < 0) {
if (left != null)
left.add(key, value);
else
left = new Node(key, value);
} else if (key.compareTo(this.key) > 0) {
if (right != null)
right.add(key, value);
else
right = new Node(key, value);
} else
this.value = value;
}
public boolean contains(Integer key) {
if (this.key.intValue() == (key)) {
return true;
}
if (key.compareTo(this.key) < 0)
return left == null ? null : left.contains(key);
else
return right == null ? null : right.contains(key);
}
}