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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- 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
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
- Iterative program to count leaf nodes in a Binary Tree
- Count half nodes in a Binary tree (Iterative and Recursive)
- Iterative Search for a key 'x' in Binary Tree
- Count full nodes in a Binary tree (Iterative and Recursive)
- Check for Symmetric Binary Tree (Iterative Approach)
- Get level of a node in binary tree | iterative approach
- Iterative diagonal traversal of binary tree
- Deepest left leaf node in a binary tree | iterative approach
- Deepest right leaf node in a binary tree | Iterative approach
- Iterative Boundary Traversal of Complete Binary tree
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )