VOOZH about

URL: https://www.geeksforgeeks.org/dsa/iterative-method-to-find-height-of-binary-tree/

⇱ Iterative Method to find Height of Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Iterative Method to find Height of Binary Tree

Last Updated : 23 Jul, 2025

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. 

👁 Example Tree

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. 

Loop
 nodeCount = size of queue
 
 // If the number of nodes at this level is 0, return height
 
 if nodeCount is 0
 return Height;
 else
 increase Height

 // Remove nodes of this level and add nodes of 
 // next level
 while (nodeCount > 0)
 push its children to queue
 pop node from front
 decrease nodeCount
 // At this point, queue has nodes of next level

Following is the implementation of the above algorithm.  


Output
The height of the binary tree using iterative method is: 3.

Time Complexity: O(n) where n is the number of nodes in a given binary tree.
Space Complexity: O(n) where n is the number of nodes in a given binary tree.

Comment
Article Tags:
Article Tags: