×

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

Stack vs Array

Difference between Array and Stack In this article, we are going to discuss the major differences between the stack and array data structures: Array – In the data structure, the array is...

3 minutes read.

Reverse a Linked List in groups of given size

Reverse a Linked List in groups of given size This article will explain how to reverse a linked list in groups of given size. Here we have given a linked list...

2 minutes read.

What is a Tree in Terms of a Graph?

To know the explanation of trees in terms of graphs, we need first to know what trees and graphs are. So let us first learn about trees and graphs. Trees and...

6 minutes read.

Insertion in B+ Tree

We will learn how to insert a node in the B+ tree and what are the different properties we are going to follow. Except for the root node, every node should...

5 minutes read.

Asynchronous advantage actor-critic (A3C) Algorithm

The Asynchronous advantage actor-critic (A3C) Algorithm is one of the latest algorithms developed by the Artificial Intelligence division, Deep Mind at Google. It is used for the Deep Reinforcement Learning...

3 minutes read.

Finding the Sum of All Paths in a Binary Tree

Implementation // Writing the C++ program to implement the below approach.  #include <bits/stdc++.h> using namespace std; // creating the new tree node structure. struct Tree__nod { int val; Tree__nod *Lft, *Rt; }; // creating a new function that will...

8 minutes read.

FLEX (Fast Lexical Analyzer Generator)

FLEX stands for Fast Lexical Analyzer Generator. Around 1987, Vern Paxson created Flex in C with a great deal of input and inspiration from Van Jacobson. Van Jacobson's approach is...

3 minutes read.

Recursion in Fibonacci

Fibonacci heap is considered to be a particular execution of the heap data structure that ultimately helps in making use of not just any number but the Fibonacci numbers. It...

3 minutes read.

Sorting Algorithms

Sorting: In the data structure, sorting is the process by which you arrange the data in a logical order. This logical order can also be an ascending order or a...

7 minutes read.

LCA of binary tree

Implementation //Writing a program to find the lowest common factor in a given binary search tree. #include <iostream> #include <vector> using namespace std; // the very first step is to create a binary tree. struct __nod { int...

8 minutes read.

Linear vs Non-Linear: Data Structure

What is Linear Data Structure? The data structure is said to be linear if the data elements are arranged linearly or we can say sequentially. In the linear data structure, the...

3 minutes read.

Merge two sorted linked lists

Merge two sorted linked lists In this article, we are going to learn how to merge two linked lists. Here we have given two linked lists that are sorted in increasing...

7 minutes read.

Given a Perfect Binary Tree, Reverse Alternate Levels

Implementation //writing a program in C++ language to see how to approach it. #include <bits/stdc++.h> using namespace std; // creating a tree node. struct Nod { char ky; struct Nod *Lft, *Rt; }; // creating a new utility function...

9 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.

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.

Binary Search Tree

Binary Search Tree: A binary search tree is a type of tree in which every node is organized in the sorted order. It is also called an ordered binary tree. Properties...

4 minutes read.

Singly Linked list

Singly Linked list A singly linked list is a kind of linked list which is unidirectional. If we talk about singly linked list, then we can say it can be traversed...

3 minutes read.

Number of visible boxes putting one inside another

You have given one array, which consists of values which represent the sizes of different boxes. We can put one box inside another if the size of the outside box...

3 minutes read.

Length of longest palindrome in a linked list using O(1) extra space

Length of longest palindrome in a linked list using O(1) extra space In this problem, we need to find the length of the longest palindrome list that is present in given...

2 minutes read.

What is a Spanning Tree in Data Structure

Data structures Data management is called database management. This allows the computer to sort or organize the data for efficient retrieval. A data model is a system used to store, manage,...

5 minutes read.