Description of the problem I need to solve: "A path per level in a tree, first list the root, then all nodes that are at level 1 then all nodes of level 2, etc. Write a procedure to list the nodes of a binary tree by level."
As it is necessary to walk through a binary tree, I used recursion in the method writing, but I can not get the expected result. Here is the method I wrote:
public void imprimeNivel(No no) {
if(no != null) {
if(no == raiz) {
System.out.println(raiz.getConteudo());
}
if(no.getFilhoDireita() == null && no.getFilhoEsquerda() == null) {
} else if(no.getFilhoDireita() == null) {
System.out.printf("%d ", no.getFilhoEsquerda().getConteudo());
} else if(no.getFilhoEsquerda() == null) {
System.out.printf("%d ", no.getFilhoDireita().getConteudo());
} else {
System.out.printf("%d ", no.getFilhoEsquerda().getConteudo());
System.out.printf("%d ", no.getFilhoDireita().getConteudo());
}
System.out.println();
imprimeNivel(no.getFilhoEsquerda());
imprimeNivel(no.getFilhoDireita());
}
}
Could someone give me an idea how to solve this problem?