The Wayback Machine - https://web.archive.org/web/20240624025918/https://www.geeksforgeeks.org/iterative-method-to-find-height-of-binary-tree/
Open In App

Iterative Method to find Height of Binary Tree

Last Updated : 21 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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, the height of the below tree is 3. 

Example Tree

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.  

C++




#include <iostream>
#include <queue>
 
using namespace std;
 
// This approach counts the number of nodes from root to the
// leaf to calculate the height of the tree.
 
// Defining the structure of a Node.
 
class Node {
public:
    int data;
    Node* left;
    Node* right;
};
 
// Helper function to create a newnode.
// Input: Data for the newnode.
// Return: Address of the newly created node.
 
Node* createNode(int data)
{
 
    Node* newnode = new Node();
    newnode->data = data;
    newnode->left = NULL;
    newnode->right = NULL;
 
    return newnode;
}
 
// Function to calculate the height of given Binary Tree.
// Input: Address of the root node of Binary Tree.
// Return: Height of Binary Tree as a integer. This includes
// the number of nodes from root to the leaf.
 
int calculateHeight(Node* root)
{
    queue<Node*> nodesInLevel;
    int height = 0;
    int nodeCount = 0; // Calculate  number of nodes in a level.
    Node* currentNode; // Pointer to store the address of a
                       // node in the current level.
    if (root == NULL) {
        return 0;
    }
    nodesInLevel.push(root);
    while (!nodesInLevel.empty()) {
        // This while loop runs for every level and
        // increases the height by 1 in each iteration. If
        // the queue is empty then it implies that the last
        // level of tree has been parsed.
        height++;
        // Create another while loop which will insert all
        // the child nodes of the current level in the
        // queue.
 
        nodeCount = nodesInLevel.size();
        while (nodeCount--) {
            currentNode = nodesInLevel.front();
 
            // Check if the current nodes has left child and
            // insert it in the queue.
 
            if (currentNode->left != NULL) {
                nodesInLevel.push(currentNode->left);
            }
 
            // Check if the current nodes has right child
            // and insert it in the queue.
            if (currentNode->right != NULL) {
                nodesInLevel.push(currentNode->right);
            }
 
            // Once the children of the current node are
            // inserted. Delete the current node.
 
            nodesInLevel.pop();
        }
    }
    return height;
}
 
// Driver Function.
 
int main()
{
    // Creating a binary tree.
 
    Node* root = NULL;
 
    root = createNode(1);
    root->left = createNode(2);
    root->left->left = createNode(4);
    root->left->right = createNode(5);
    root->right = createNode(3);
 
    cout << "The height of the binary tree using iterative "
            "method is: " << calculateHeight(root) << ".";
 
    return 0;
}


Java




// An iterative java program to find height of binary tree
  
import java.util.LinkedList;
import java.util.Queue;
  
// A binary tree node
class Node
{
    int data;
    Node left, right;
  
    Node(int item)
    {
        data = item;
        left = right;
    }
}
  
class BinaryTree
{
    Node root;
  
    // Iterative method to find height of Binary Tree
    int treeHeight(Node node)
    {
        // Base Case
        if (node == null)
            return 0;
  
        // Create an empty queue for level order traversal
        Queue<Node> q = new LinkedList();
  
        // Enqueue Root and initialize height
        q.add(node);
        int height = 0;
  
        while (1 == 1)
        {
            // nodeCount (queue size) indicates number of nodes
            // at current level.
            int nodeCount = q.size();
            if (nodeCount == 0)
                return height;
            height++;
  
            // Dequeue all nodes of current level and Enqueue all
            // nodes of next level
            while (nodeCount > 0)
            {
                Node newnode = q.peek();
                q.remove();
                if (newnode.left != null)
                    q.add(newnode.left);
                if (newnode.right != null)
                    q.add(newnode.right);
                nodeCount--;
            }
        }
    }
  
    // Driver program to test above functions
    public static void main(String args[])
    {
        BinaryTree tree = new BinaryTree();
         
        // Let us create a binary tree shown in above diagram
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);
        System.out.println("Height of tree is " + tree.treeHeight(tree.root));
    }
}
  
// This code has been contributed by Mayank Jaiswal


Python3




# Program to find height of tree by Iteration Method
 
# A binary tree node
class Node:
     
    # Constructor to create new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Iterative method to find height of Binary Tree
def treeHeight(root):
     
    # Base Case
    if root is None:
        return 0
     
    # Create a empty queue for level order traversal
    q = []
     
    # Enqueue Root and Initialize Height
    q.append(root)
    height = 0
 
    while(True):
         
        # nodeCount(queue size) indicates number of nodes
        # at current level
        nodeCount = len(q)
        if nodeCount == 0 :
            return height
     
        height += 1
 
        # Dequeue all nodes of current level and Enqueue
        # all nodes of next level
        while(nodeCount > 0):
            node = q[0]
            q.pop(0)
            if node.left is not None:
                q.append(node.left)
            if node.right is not None:
                q.append(node.right)
 
            nodeCount -= 1
 
 
# Driver program to test above function
# Let us create binary tree shown in above diagram
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
 
print ("Height of tree is", treeHeight(root))
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)


C#




// An iterative C# program to
// find height of binary tree
using System;
using System.Collections.Generic;
 
// A binary tree node
class Node
{
    public int data;
    public Node left, right;
 
    public Node(int item)
    {
        data = item;
        left = right;
    }
}
 
public class BinaryTree
{
    Node root;
 
    // Iterative method to find
    // height of Binary Tree
    int treeHeight(Node node)
    {
        // Base Case
        if (node == null)
            return 0;
 
        // Create an empty queue
        // for level order traversal
        Queue<Node> q = new Queue<Node>();
 
        // Enqueue Root and initialize height
        q.Enqueue(node);
        int height = 0;
 
        while (1 == 1)
        {
            // nodeCount (queue size) indicates
            // number of nodes at current level.
            int nodeCount = q.Count;
            if (nodeCount == 0)
                return height;
            height++;
 
            // Dequeue all nodes of current
            // level and Enqueue all
            // nodes of next level
            while (nodeCount > 0)
            {
                Node newnode = q.Peek();
                q.Dequeue();
                if (newnode.left != null)
                    q.Enqueue(newnode.left);
                if (newnode.right != null)
                    q.Enqueue(newnode.right);
                nodeCount--;
            }
        }
    }
 
    // Driver code
    public static void Main(String []args)
    {
        BinaryTree tree = new BinaryTree();
         
        // Let us create a binary
        // tree shown in above diagram
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);
        Console.WriteLine("Height of tree is " +
                        tree.treeHeight(tree.root));
    }
}
 
// This code has been contributed by 29AjayKumar


Javascript




<script>
// An iterative javascript program to find height of binary tree
 
// A binary tree node
class Node
{
    constructor(item)
    {
        this.data = item;
        this.left = this.right=null;
    }
}
 
let root;
 
// Iterative method to find height of Binary Tree
function treeHeight(node)
{
 
    // Base Case
        if (node == null)
            return 0;
   
        // Create an empty queue for level order traversal
        let q = [];
   
        // Enqueue Root and initialize height
        q.push(node);
        let height = 0;
   
        while (1 == 1)
        {
            // nodeCount (queue size) indicates number of nodes
            // at current level.
            let nodeCount = q.length;
            if (nodeCount == 0)
                return height;
            height++;
   
            // Dequeue all nodes of current level and Enqueue all
            // nodes of next level
            while (nodeCount > 0)
            {
                let newnode = q.shift();
                if (newnode.left != null)
                    q.push(newnode.left);
                if (newnode.right != null)
                    q.push(newnode.right);
                nodeCount--;
            }
        }
}
 
// Driver program to test above functions
// Let us create a binary tree shown in above diagram
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
document.write("Height of tree is " + treeHeight(root));
 
// This code is contributed by rag2127
</script>


Output

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.



Similar Reads

Check whether a binary tree is a full binary tree or not | Iterative Approach
Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. Examples: Input : 1 / \ 2 3 / \ 4 5 Outp
8 min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Iterative method to find ancestors of a given binary tree
Given a binary tree, print all the ancestors of a particular key existing in the tree without using recursion.Here we will be discussing the implementation for the above problem. Examples: Input : 1 / \ 2 7 / \ / \ 3 5 8 9 / \ / 4 6 10 Key = 6 Output : 5 2 1 Ancestors of 6 are 5, 2 and 1. The idea is to use iterative postorder traversal of given bi
12 min read
Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
There are two common ways to traverse a graph, BFS and DFS. Considering a Tree (or Graph) of huge height and width, both BFS and DFS are not very efficient due to following reasons. DFS first traverses nodes going through one adjacent of root, then next adjacent. The problem with this approach is, if there is a node close to root, but not in first
10 min read
Check if a given Binary Tree is height balanced like a Red-Black Tree
In a Red-Black Tree, the maximum height of a node is at most twice the minimum height (The four Red-Black tree properties make sure this is always followed). Given a Binary Search Tree, we need to check for following property. For every node, length of the longest leaf to node path has not more than twice the nodes on shortest path from node to lea
9 min read
Iterative Method To Print Left View of a Binary Tree
Given a Binary Tree, print it's left view. Left view of a Binary Tree is a set of nodes visible when tree is seen from the left side . Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 1 2 4 Input : 1 / \ 2 3 \ / 4 5 \ 6 / \ 7 8 Output : 1 2 4 6 7 We have already discussed this problem using the Recursion method, here iterative approach is used
13 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Convert a Binary Tree into its Mirror Tree (Invert Binary Tree)
Given a binary tree, the task is to convert the binary tree into its Mirror tree. Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. Recommended PracticeMirror TreeTry It!The idea is to traverse recursively and swap the right and left subtrees after traversing the subtrees. Follow
15+ min read
Find the Maximum Depth or Height of given Binary Tree
Given a binary tree, the task is to find the height of the tree. The height of the tree is the number of vertices in the tree from the root to the deepest node. Note: The height of an empty tree is 0 and the height of a tree with single node is 1. Recommended PracticeHeight of Binary TreeTry It!Recursively calculate the height of the left and the r
15+ min read
Find Height of Binary Tree represented by Parent array
A given array represents a tree in such a way that the array value gives the parent node of that particular index. The value of the root node index would always be -1. Find the height of the tree. The height of a Binary Tree is the number of nodes on the path from the root to the deepest leaf node, and the number includes both root and leaf. Input:
13 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg