Reputation: 329
I have this code:
private String buscar(Nodo nodo, Nodo raiz) {
System.out.println(nivel);
this.nivel++;
if (raiz != null) {
if (nodo.getValor() == raiz.getValor()) {
System.out.println("es igual");
return "El número " + nodo.getValor() + " está en el nivel: " + this.nivel;
} else if (nodo.getValor() < raiz.getValor()) {
buscar(nodo, raiz.getIzq());
} else {
System.out.println("es mayor");
buscar(nodo, raiz.getDer());
}
} else {
return "El número " + nodo.getValor() + " no forma parte del árbol";
}
return null;
}
public String buscar(int valor) {
this.nivel = 0;
Nodo nodo = new Nodo(valor);
return this.buscar(nodo, this.raiz);
}
and is always execute the last return sentence (return null), even when the if sentence becomes true. Can anybody tell me why this is happening?
Upvotes: 0
Views: 157
Reputation: 201467
You need to return
the result of your recursive calls, you can also eliminate two of the else
conditions (since you return
). And, I would prefer String.format
over concatenation. Like,
private String buscar(Nodo nodo, Nodo raiz) {
System.out.println(nivel);
this.nivel++;
if (raiz != null) {
if (nodo.getValor() == raiz.getValor()) {
System.out.println("es igual");
return String.format("El número %d está en el nivel: %d",
nodo.getValor(), this.nivel);
} else if (nodo.getValor() < raiz.getValor()) {
return buscar(nodo, raiz.getIzq()); // return the recursive result
}
System.out.println("es mayor");
return buscar(nodo, raiz.getDer()); // return the recursive result
}
return String.format("El número %d no forma parte del árbol", nodo.getValor());
}
Upvotes: 1