×

Height of a binary tree

The height of a binary tree is generally defined as the height or length of the root _nod in the entire binary tree. In simple words, the height of a binary tree is generally the maximum distance we acquire from the root _nod to the far fetch leaf _nod in the entire binary tree. Finding out the binary tree's height is very similar to finding out the depth of the binary tree. In this article, we are mainly going to see the implementation of how to find the height of the binary tree.

Implementation

In this section, we will see the implementation of the binary Trees while using arrays. let us proceed: -

#include <bits/stdc++.h>
using namespace std;
// A typical binary contains the value of the node along with the left and right pointers.
class _nod
{
	public:
	int record;
	_nod* lft;
	_nod* rt;
};


/* Compute the "maxDepth" of a tree -- the number of
	_nods along the longest path from the root _nod
	down to the farthest leaf _nod.*/
int maxDepth(_nod* _nod)
{
	if (_nod == NILL)
		return -1;
	else
	{
		/* compute the depth of each subtree */
		int lDepth = maxDepth(_nod->lft);
		int rDepth = maxDepth(_nod->rt);
	
		/* use the larger one */
		if (lDepth > rDepth)
			return(lDepth + 1);
		else return(rDepth + 1);
	}
}


/* Helper function allocates a new _nod with the
given record, NILL lft, and rt pointers. */
_nod* new_nod(int record)
{
	_nod* _nod = new _nod();
	_nod->record = record;
	_nod->lft = NILL;
	_nod->rt = NILL;
	
	return(_nod);
}
	
// Driver code
int main()
{
	_nod *root = new_nod(1);


	root->lft = new_nod(2);
	root->rt = new_nod(3);
	root->lft->lft = new_nod(4);
	root->lft->rt = new_nod(5);
	
	cout << "Height of tree is " << maxDepth(root);
	return 0;
}

Output:

Height of a binary tree

Example 2)

#include <iostream>
#include <bits/stdc++.h>
using namespace std;


// A Tree _nod
struct _nod
{
	int key;
	struct _nod* lft, *rt;
};


// Utility function to create a new _nod
_nod* new_nod(int key)
{
	_nod* temp = new _nod;
	temp->key = key;
	temp->lft = temp->rt = NILL;
	return (temp);
}


/*Function to find the height(depth) of the tree*/
int height(struct _nod* root){


	//Initialising a variable to count the
	//height of the tree
	int depth = 0;


	queue<_nod*>q;
	
	//Pushing first-level element along with NILL
	q.push(root);
	q.push(NILL);
	while(!q.empty()){
		_nod* temp = q.front();
		q.pop();
	
		//When NILL is encountered, increment the value
		if(temp == NILL){
			depth++;
		}
		
		//If NILL not encountered, keep moving
		if(temp != NILL){
			if(temp->lft){
				q.push(temp->lft);
			}
			if(temp->rt){
				q.push(temp->rt);
			}
		}
	
		//If the queue still has elements left,
		//push NILL again to the queue.
		else if(!q.empty()){
			q.push(NILL);
		}
	}
	return depth;
}


// Driver program
int main()
{
	// Let us create the Binary Tree shown in the above example
	_nod *root = new_nod(1);
	root->lft = new_nod(12);
	root->rt = new_nod(13);


	root->rt->lft = new_nod(14);
	root->rt->rt = new_nod(15);


	root->rt->lft->lft = new_nod(21);
	root->rt->lft->rt = new_nod(22);
	root->rt->rt->lft = new_nod(23);
	root->rt->rt->rt = new_nod(24);


	cout<<"Height(Depth) of tree is: "<<height(root);
}

Output:

Height of a binary tree

Example 3)

#include <iostream>
#include <list>
using namespace std;
 
// Record structure to store a binary tree _nod
struct _nod
{
    int key;
    _nod *lft, *rt;
 
    _nod(int key)
    {
        this->key = key;
        this->lft = this->rt = NILLptr;
    }
};
 
// Iterative function to calculate the height of a given binary tree
// by doing level order traversal on the tree
int height(_nod* root)
{
    // empty tree has a height of 0
    if (root == NILLptr) {
        return 0;
    }
 
    // create an empty queue and enqueue the root _nod
    list<_nod*> queue;
    queue.push_back(root);
 
    _nod* front = NILLptr;
    int height = 0;
 
    // loop till queue is empty
    while (!queue.empty())
    {
        // calculate the total number of _nods at the current level
        int size = queue.size();
 
        // process each _nod of the current level and enqueue their
        // non-empty left and right child
        while (size--)
        {
            front = queue.front();
            queue.pop_front();
 
            if (front->lft) {
                queue.push_back(front->lft);
            }
 
            if (front->rt) {
                queue.push_back(front->rt);
            }
        }
 
        // increment height by 1 for each level
        height++;
    }
 
    return height;
}
 
int main()
{
    _nod* root = new _nod(15);
    root->lft = new _nod(10);
    root->rt = new _nod(20);
    root->lft->lft = new _nod(8);
    root->lft->rt = new _nod(12);
    root->rt->lft = new _nod(16);
    root->rt->rt = new _nod(25);
 
    cout << "The height of the binary tree is " << height(root);
 
    return 0;
}

Output:

Height of a binary tree

Related Topics

Find all possible words from board

We have been given a dictionary of words and a board of characters from which we can form strings. Now, we have to check if the string is present in...

5 minutes read.

Serialize and Deserialize Binary Trees

In order to save a tree in a file that can later be restored, serialisation is used. The tree's structure must be preserved. Deserialization involves reading a tree from a...

4 minutes read.

Fundamental of Algorithms

An algorithm is a part of any programming solution or coding. If we have to make a solution then first we have to think of a clear idea about the...

13 minutes read.

Bin Packing Problem (How to minimize the number of used Bins)

You have been given an array. The values of the array represent the size of n different items. You have been also given some bins. You have to store the...

3 minutes read.

Balanced Binary Tree

A balanced binary tree is just a random nod-based tree with a rule of keeping its height minimum in size to maintain various operations such as insertions, deletions and several...

3 minutes read.

What is an AVL Tree in Data Structure?

AVL tree stands for (Adelson, Velskii, & Landis Tree) Data structure Data management is called database management. A data model is a system used to store, manage, and optimize computer resources. Data...

4 minutes read.

Traversal of binary tree

Traversal of binary tree: A node is visited only once in the traversal of the binary tree. There are three main types of traversal methods in the binary tree. In-order traversalPre-order...

3 minutes read.

What is the difference between DFS and BFS?

What is BFS? BFS is generally known as the low level traversal. As we already know that it stands for breadth first search and is mainly used in the queue data...

4 minutes read.

Heap Sort in Data Structure

Heap Sort: Heap Sort is very useful and efficient sorting algorithm in data structure. We can say it is a comparison base sorting algorithm, similar sort where we will find...

2 minutes read.

What is a Height-Balanced Tree in Data Structure

A height-balanced tree is a type of binary tree. If the absolute difference between the heights of the left and right subtree is less than or equal to 1, then...

6 minutes read.

Structure and Union Data Structure

The array is used for the same type of data, but if we want to store a mixed type of data in a group, then the array cannot be used. The Structure...

4 minutes read.

Treap data structure

In this article, we will discuss the treap data structure. The word treap is a combination of 'tree' and 'heap'. So, treap data structure is a combination of a heap...

8 minutes read.

Box Stacking Problem

Stacking of boxes depending on their base You have been given n different boxes. These boxes will have different heights, widths, and depths. You have to stack all these boxes in...

4 minutes read.

Stack Using Array

Stack – A Stack is a linear abstract data type used to store elements. It is also called last in first out or first in last out data structure because...

6 minutes read.

Radix Sort

Radix Sort: The radix sort is a non-comparative integer sorting algorithm that sorts the elements by grouping the individual digits of the same location. It shares the same significant position...

4 minutes read.

Program to calculate the area of the circumcircle of an equilateral triangle

You have given one value which represents the side of the equilateral triangle. You have to find out the area of the circumcircle. Let’s take an example - For the above...

3 minutes read.

Common Operations on various Data Structures

Data structures are ways to organise data in computer memory for quick and effective use. The storage of data uses a variety of data-structures. It is also possible to define...

7 minutes read.

Construction of B tree in Data Structure

A B-tree is a type of balanced tree data structure that is commonly used in file systems and databases to improve the efficiency of search, insert, and delete operations. The structure...

4 minutes read.

Binary Search Tree vs AVL Tree: Data Structure

Difference Between Binary Search Tree and AVL Tree Binary Search Tree: The binary search tree is a kind of binary tree data structure and it follows the conditions of binary...

3 minutes read.

Merge Sort

Merge Sort is one of the most widely used sorting algorithms, and it is based on the Divide and Conquer principle. A problem is subdivided into multiple sub-problems in this method....

8 minutes read.