Así que estoy leyendo de un archivo (consiste en nombre y salario) y lo estoy insertando en un árbol. Después de eso, estoy haciendo un método de búsqueda. Está funcionando e imprimiendo verdadero si el nodo existe. ¿Cómo imprimo el nombre real y el salario simplemente buscando por salario? Aquí está mi método de búsqueda:
public boolean find(int salary) { Add current = root; while (current != null) { if (current.getSalary() == salary) { return true; } else if (current.getSalary() > salary) { current = current.getLeft(); } else { current = current.getRight(); } } return false; }
Y aquí está mi método principal:
public static void main(String[] args) throws IOException { BinaryTree bt = new BinaryTree(); bt.readfile(); bt.print(bt.root); System.out.println(); System.out.println("Find method: return true if a node exits ,else return flase"); System.out.println(bt.find(8900));`
Si find()
devuelve un nodo, escriba un método toString()
para el nodo de modo que se exprese el nombre.
Ejemplo:
@Override public String toString(){ return this.name + " " + this.salary; }
Por qué esto funciona:
Cuando System.out.println()
llame a su nodo, automáticamente llamará a la dirección de memoria. Si anula esta llamada con su método personalizado, puede definir qué variables se imprimen.