×

Depth of binary tree

We all know that a binary tree is a kind of tree that helps us maintain the order and balance of the tree. It is a type of tree in which each node present in the tree usually consists of at least two nodes at every point. The word binary itself means 'two' of anything.

The word depth means how deep is a certain thing or the impact of being intense. It is the difference between the two surfaces. The depth of a binary tree is mainly described as the total number of nodes present along the longest path from the root node to the last leaf node.

Implementation

In this section, we will see the implementation of how to find out the depth of a binary tree.

//creating a c++ program to determine the Depth of a binary tree.
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node mainly comprises a value and a pointer to the left and right child. 
class _nod
{
	public:
	int record;
	_nod* lft;
	_nod* rt;
};


/*Calculating the maximum Depth of the tree and the number of nodes. 
int maxDep(_nod* _nod)
{
	if (_nod == NILL)
		return -1;
	else
	{
		//calculate the Depth of every subtree that is present.
		int lDep = maxDep(_nod->lft);
		int rDep = maxDep(_nod->rt);
	
		//using the one that is bigger in size.
		if (lDep > rDep)
			return(lDep + 1);
		else return(rDep + 1);
	}
}


/* creating a helper function that helps us create a new node and allocate it to the given nodes along with the left and right pointers. */
_nod* nw_nod(int record)
{
	_nod* _nod = new _nod();
	_nod->record = record;
	_nod->lft = NILL;
	_nod->rt = NILL;
	
	return(_nod);
}
	
// Driver code
int main()
{
	_nod *root = nw_nod(1);


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

Output:

Depth of binary tree

Example 2)

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
//creating a node for the tree.
struct _nod
{
	int ky;
	struct _nod* lft, *rt;
};


// creating a utility function that will eventually help us build a new node.
_nod* nw_nod(int ky)
{
	_nod* temp = new _nod;
	temp->ky = ky;
	temp->lft = temp->rt = NILL;
	return (temp);
}


/* creating a function that will help us find the height or depth of the given binary tree. */
int height(struct _nod* root){


	//initializing a variable that will help us count the height or, say, the depth of the binary tree.
	int Dep = 0;


	queue<_nod*>c;
	
	//we have to penetrate or push the element along with the NULL value.
	c.push(root);
	c.push(NILL);
	while(!c.empty()){
		_nod* temp = c.front();
		c.pop();
	
		//if we find the NILL value, we must increment the given value.
		if(temp == NILL){
			Dep++;
		}
		
		// if we don’t find the NILL value, we must keep moving.
		if(temp != NILL){
			if(temp->lft){
				c.push(temp->lft);
			}
			if(temp->rt){
				c.push(temp->rt);
			}
		}
	
		//If the queue still has elements left,
		//push NILL again to the queue.
		else if(!c.empty()){
			c.push(NILL);
		}
	}
	return Dep;
}


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


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


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


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

Output:

Depth of binary tree

Example 3)

#include <iostream>
using namespace std;


struct _nod {
	int info;
	_nod *lft, *rt;


	_nod(int info)
	{
		this->info = info;
		this->lft = this->rt = NILL;
	}
};


int maxDep(_nod * root)
{
  // here, the root is NILL which implies that the tree doesn't exist.
  if (root == NILL)
    return 0;
  
  // get the depth of the left and right subtrees while using the recursion.
  int lftDep = maxDep(root->lft);
  int rtDep = maxDep(root->rt);


  // choose the one that has the larger size and add root to it.
  if (lftDep > rtDep)
    return lftDep + 1;
  else
    return rtDep + 1;
}


// 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->rt->lft = new _nod(5);
  root->rt->rt = new _nod(6);
  root->rt->rt->lft = new _nod(8);
  root->rt->lft->rt = new _nod(7);
  cout << "The maximum Dep is: " << maxDep(root) << endl;
}

Output:

Depth of binary tree

Related Topics

Array Data Structure

Data Structure Array: The array is a non-primitive and linear data structure that is a group of similar data items. That is, it can store only one type of data....

6 minutes read.

Binary Search

Binary Search: When there is a large data structure, the linear search takes a lot of time to search the element. The binary search was developed to overcome the lack...

7 minutes read.

Linear Search

Searching: In the data structure, searching is the process in which an element is searched in a list that satisfies one or more than one condition. Types of searching There are two...

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

Insertion Sort in Data Structures

Insertion Sort in C++ Insertion sort is a sorting algorithm that, in each iteration, installs an unsorted element in its proper position Insertion sort operates in a similar way to how we...

3 minutes read.

All About Minimum Cost Spanning Trees in Data Structure

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 that stores, manages, and optimizes...

7 minutes read.

Threaded Binary Tree

The linked form of binary trees wastes storage capacity because more than half of the connection variables have a Missing value. A binary tree has several nodes. Hence n+1 link fields...

8 minutes read.

Understanding Data Processing

Introduction Data In our everyday lives, any task that we perform online is related to data. Millions of pieces of data are produced every second across the globe. Data production is largely...

4 minutes read.

Breadth First Search

Breadth First Search Breadth first search is a graph traversing algorithm. In this, we start traversing from the source node or any selected node and traverse the graph layer by layer....

6 minutes read.

Types of Data Structures

Almost every programme or software system that has been built makes use of data structures. Furthermore, data structures are basics of computer science and software engineering. When it comes to...

7 minutes read.

Circular Queue

Circular Queue Circular Queue is special type queue, which follows First in First Out (FIFO) rule and as well as instead of ending queue at the last position, it starts again...

4 minutes read.

Heap Sort in Data Structure

Heap Sort A heap is a tree-based data structure that has specific properties. Heap is always a complete binary tree (CBT). That is, all the nodes of the tree are completely filled.If...

6 minutes read.

Quick Sort

Quicksort is a sorting algorithm that uses a divide-and-conquer strategy. A pivot element is used to divide an array into subarrays (element selected from the array).  The pivot element should be...

4 minutes read.

Given a Binary Tree Return All Root-to-Leaf Paths

Implementation #include <bits/stdc++.h> using namespace std; // A binary tree node generally consists of data, a pointer to the left and right child, and a pointer to the right child.  class __nod { public: int record; __nod* Lft; __nod*...

9 minutes read.

Function to Create a Copy of Binary Search Tree

Implementation // creating a new hashmap in the language C++ that will help us clone a binary tree with arbitrary pointers.  #include<iostream> #include<unordered_map> using namespace std; /* A given binary tree has a record, a...

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

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.

Difference between Stack and Queue

In this article, we will learn about the major differences between Stack and Queue data structures. What is a stack? Stack – A stack is an abstract data structure defined as the...

3 minutes read.

Tree vs Graph: Data Structure

Difference Between Tree and Graph What is Tree? A tree is a non-linear data structure and finite collection of elements called node. A tree, in which the data items are arranged in...

3 minutes read.

Priority Queue in Data Structure

Priority Queue A priority queue is a special kind of queue, in priority queue we give some priority to an element and according to this priority an element can be served...

3 minutes read.