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 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) pop node from front push its children to queue decrease nodeCount // At this point, queue has nodes of next level
Following is the implementation of above algorithm.
Height of tree is 3
Time Complexity: O(n) where n is number of nodes in given binary tree.
This article is contributed by Rahul Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Iterative method to find ancestors of a given binary tree
- Find Height of Binary Tree represented by Parent array
- Find height of a special binary tree whose leaf nodes are connected
- Iterative Method To Print Left View of a Binary Tree
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Height of binary tree considering even level leaves only
- How to determine if a binary tree is height-balanced?
- Iterative Search for a key 'x' in Binary Tree
- Relationship between number of nodes and height of binary tree
- Height of a complete binary tree (or Heap) with N nodes
- Iterative diagonal traversal of binary tree
- Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
- Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
- Check for Symmetric Binary Tree (Iterative Approach)