There are two conventions to define height of Binary Tree
1) Number of nodes on longest path from root to the deepest node.
2) Number of edges on longest path from 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 count of nodes at next level is 0.
Following is detailed algorithm to find level order traversal using queue.
Create a queue. Push root into the queue. height = 0 Loop nodeCount = size of queue // If 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
- 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
- How to determine if a binary tree is height-balanced?
- Height of binary tree considering even level leaves only
- Relationship between number of nodes and height of binary tree
- Height of a complete binary tree (or Heap) with N nodes
- Iterative Search for a key 'x' in Binary Tree
- Iterative diagonal traversal of binary tree
- Print middle level of perfect binary tree without finding height
- Check for Symmetric Binary Tree (Iterative Approach)
- Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
- Iterative Boundary traversal of Complete Binary tree