Both height with the amount of elements are much easier recursively using a Depth First Search (DFS) algorithm, like this:
public int nivel(Node no){
if (no == null) return 0;
return (int)Math.max(nivel(no.getNodeEsquerda())+1, nivel(no.getNodeDireita())+1);
}
Using Breadth First Search (BFS), which is your example, these are more complex and / or extensive, although they have other properties, for example, to go from level to level instead of in depth.
Your code is doing the following:
- Starts from 8 increases to level 1 and stacks 3 and 10.
- Then parse the 3, increase the level to 2, and stack the 1 and the 6
- Next goes to 10, and raises the level to 3 by stacking 13
At this point it is no longer right because 3
and 10
are still at the same level. So the code will increase for each node giving the amount of nodes instead of the height.
One solution I see is to also stack the node level so that each node considers the level of the parent node to discover its own, and its always the one of the parent plus 1. To facilitate it one can create an auxiliary class that has a reference to Node
and its nivel
, modifying Queue
to use that type
Example:
private class NodeNivel { //classe para ter No e Nivel
public Node no;
public int nivel;
public NodeNivel(Node no, int nivel){
this.no = no;
this.nivel = nivel;
}
}
public int nivel(){
Node aux = raiz;
int nivel = 0;
if (aux == null) throw new IllegalArgumentException("Arvore vazia.");
Deque<NodeNivel> fila = new ArrayDeque<>(); //Agora Deque<NodeNivel>
//cada vez que empilha leva nivel tambem,que é 1 para a raiz
fila.add(new NodeNivel(aux, 1));
while (!fila.isEmpty()) {
NodeNivel atual = fila.removeFirst(); //Agora NodeNivel
//estes ifs agora empilham NodeNivel aumentando o nivel em 1
if (atual.no.getNodeEsquerda() != null)
fila.add(new NodeNivel(atual.no.getNodeEsquerda(), atual.nivel+1));
if (atual.no.getNodeDireita() != null)
fila.add(new NodeNivel(atual.no.getNodeDireita(), atual.nivel+1));
//verifica e atualiza o nivel maximo
if (atual.nivel > nivel)
nivel = atual.nivel;
}
return nivel;
}