I'm trying to do this with a ArrayList
, but I'm not understanding how to insert a ArrayList
within a ArrayList
in a recursive or interactive way even though the tree has no defined limit.
This is not what you should do. This is a XY problem .
Java is an object-oriented language. Keeping recursive lists of numbers is not an object-oriented way of attacking your problem. This means that this approach probably will not work. If you can get it to work, the result will be a good gambiarra.
The best way would be to see what objects are involved in this:
You have a Arvore
.
The Arvore
has a% root%.
Each No
can have several other No
s below it.
Each No
stores an integer.
Turning these four requirements into code:
public class Arvore {
private No raiz;
}
import java.util.List;
public class No {
private int conteudo;
private List<No> filhos;
}
Ok, now that we have the general structure of our classes, let's define some methods and constructors:
public class Arvore {
private No raiz;
public Arvore(int conteudoRaiz) {
this.raiz = new No(conteudoRaiz);
}
public No getRaiz() {
return raiz;
}
public No buscar(int procurado) {
raiz.buscar(procurado);
}
}
import java.util.ArrayList;
import java.util.List;
public class No {
private int conteudo;
private List<No> filhos;
public No(int conteudo) {
this.filhos = new ArrayList<>();
this.conteudo = conteudo;
}
public No acrescentarFilho(int conteudoFilho) {
No n = new No(conteudoFilho);
filhos.add(n);
return n;
}
public int getConteudo() {
return conteudo;
}
public List<No> getFilhos() {
return filhos;
}
public No buscar(int procurado) {
if (procurado == conteudo) return this;
for (No filho : filhos) {
No achou = filho.buscar(procurado);
if (achou != null) return achou;
}
return null;
}
}
You can go adding other methods to accomplish the jobs you want, but the point here is that you have to have well defined what each thing is. Saying that a tree is a list or that a tree node is a list just leaves things complicated and confusing and probably will not work. Ideally, the tree has a root node, that a node has a list of other nodes. Note that the verb is important: the and concept concept completely changes the way you structure your code.