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, the height of the below tree is 3.
The recursive method to find the height of the 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 = 0 // Number of nodes in the current level.
// If the number of nodes in the queue is 0, it implies that all the levels of the tree
// have been parsed. So, return the height. Otherwise count the number of nodes in the current
// level and push the children of all the nodes in the current level to the queue.
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)
push its children to queue
pop node from front
// At this point, queue has nodes of next level