There are two conventions to define the height of a Binary Tree 1) Number of nodes on the longest path from the root to the deepest node. 2) Number of edges on the longest path from the root to the deepest node.
In this post, the first convention is followed. For example, height of the below tree is 3.
Recursive method to find height of Binary Tree is discussed here. How to find height without recursion? We can use level order traversal to find height without recursion. The idea is to traverse level by level. Whenever move down to a level, increment height by 1 (height is initialized as 0). Count number of nodes at each level, stop traversing when the count of nodes at the next level is 0. Following is a detailed algorithm to find level order traversal using a queue.
Create a queue.
Push root into the queue.
height = 0
nodeCount = size of queue
// If the number of nodes at this level is 0, return height
if nodeCount is 0
// Remove nodes of this level and add nodes of
// next level
while (nodeCount > 0)
pop node from front
push its children to queue
// At this point, queue has nodes of next level