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 if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- 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
- 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
- How to determine if a binary tree is height-balanced?
- Relationship between number of nodes and height of binary tree
- Height of a complete binary tree (or Heap) with N nodes
- Calculate height of Binary Tree using Inorder and Level Order Traversal
- Height of binary tree considering even level leaves only
- Print middle level of perfect binary tree without finding height
- Print the nodes of the Binary Tree whose height is a Prime number
- Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
- 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)