![]() |
VOOZH | about |
There are two conventions to define the height of a Binary Tree
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. 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.
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.