This is same as the number of nodes in the longest path. We can see that longest path with just one node is 1 i.e. the node itself. So, height aka max depth aka longest path is one more than the max of left or right sub tree height.
publicstaticintmaxDepth(Node root) {
// empty tree has a height of 0if (root ==null) {
return 0;
}
// create an empty queue and enqueue the root node Queue<Node> queue =new ArrayDeque<>();
queue.add(root);
Node front =null;
int height = 0;
// loop till queue is emptywhile (!queue.isEmpty())
{
// calculate the total number of nodes at the current levelint size = queue.size();
// process each node of the current level and enqueue their// non-empty left and right childwhile (size--> 0)
{
front = queue.poll();
if (front.left!=null) {
queue.add(front.left);
}
if (front.right!=null) {
queue.add(front.right);
}
}
// increment height by 1 for each level height++;
}
return height;
}