I have tried to work with this function but the only thing it does is fill the root I try to make a binary tree and when I input the values the only thing it does is the root does not add children neither to the left nor to the right what happens is that for example I enter 2 then 3 then 1 the father would have to be 2 left son 1 right son 3 but the only thing that this does is get only the father if I put 2 the father is 2 if I put 3 the father is 3 does not make the tree only the root is added
Here is my method below the class where you are
public void addNodo(Nodo nodo, Nodo raiz) {
Principal p = new Principal();
if (raiz==null) {
this.setRaiz(nodo);
System.out.println("Agrego raiz");
} else if (nodo.getValor() <= raiz.getValor()) {
if (raiz.getHojaIzquierda() == null) {
raiz.setHojaIzquierda(nodo);
} else {
addNodo(nodo, raiz.getHojaIzquierda());
}
System.out.println("Agrego izquierda");
} else{
if (raiz.getHojaDerecha() == null) {
raiz.setHojaDerecha(nodo);
} else {
addNodo(nodo, raiz.getHojaDerecha());
}
System.out.println("Agrego derecha");
}
}
I have my node class
public class Nodo {
/* Declaraciones de variables */
private int valor;
private Nodo padre;
private Nodo hojaIzquierda;
private Nodo hojaDerecha;
/* Constructor */
public Nodo(int valor) {
this.valor = valor;
}
/* Setters y Getters */
public void setValor(int valor) {
this.valor = valor;
}
public int getValor() {
return valor;
}
public Nodo getPadre() {
return padre;
}
public void setPadre(Nodo padre) {
this.padre = padre;
}
public Nodo getHojaIzquierda() {
return hojaIzquierda;
}
public void setHojaIzquierda(Nodo hojaIzquierda) {
this.hojaIzquierda = hojaIzquierda;
}
public Nodo getHojaDerecha() {
return hojaDerecha;
}
public void setHojaDerecha(Nodo hojaDerecha) {
this.hojaDerecha = hojaDerecha;
}
@Override
public String toString() {
return ""+valor;
}
}
This is my tree class
public class Arbol {
/* Atributos */
public Arbol() {
}
private Nodo raiz;
/* Contructories */
public Arbol(int valor) {
this.raiz = new Nodo(valor);
}
public Arbol(Nodo raiz) {
this.raiz = raiz;
}
/* Setters y Getters */
public Nodo getRaiz() {
return raiz;
}
public void setRaiz(Nodo raiz) {
this.raiz = raiz;
}
// Here is my method with problems public void addNode (Node node, root node) { Principal p = new Principal ();
if (raiz==null) {
this.setRaiz(nodo);
System.out.println("Agrego raiz");
} else if (nodo.getValor() <= raiz.getValor()) {
if (raiz.getHojaIzquierda() == null) {
raiz.setHojaIzquierda(nodo);
} else {
addNodo(nodo, raiz.getHojaIzquierda());
}
System.out.println("Agrego izquierda");
} else{
if (raiz.getHojaDerecha() == null) {
raiz.setHojaDerecha(nodo);
} else {
addNodo(nodo, raiz.getHojaDerecha());
}
System.out.println("Agreago derecha");
}
}
public void addNodo(Nodo nodo) {
this.addNodo(nodo, this.raiz);
}