×

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

FIFO approach

FIFO is first in first out approach. It is done for the list of elements in data structures where first element will be deleted after another element ia added to it Here,...

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

Queue Data Structure

Queue in DS: The queue is a non-primitive and linear data structure. It works on the principle of FIFO (First In First Out). That is, the element that is added...

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.

Given a Binary Tree, Check if it's balanced

Implementation /*Creating a C++ program that will help us identify whether the given tree is height-balanced or not.  */ #include <bits/stdc++.h> using namespace std; /* A particular binary tree node consists of data with some...

4 minutes read.

Types of Linked list

Single linked list  A single linked list is a linked list in which all nodes are connected with each other in sequence. Each node of a singly linked list has two...

7 minutes read.

Assembly Line Scheduling

If we take an example of a car factory, there are two assembly lines. In an assembly line, we can assemble and repair the parts of a car. Now, suppose...

5 minutes read.

Compare Balanced Binary Tree and Complete Binary Tree

Complete and balanced binary trees are important and general topics in the concept – Tree data structure. Before discussing the complete and balanced binary tree, we need to have an...

8 minutes read.

Circular Linked List

Circular Linked List A circular linked list where all nodes are connected to their next node and last node is connected to the starting node or we can say all nodes...

5 minutes read.

Flattening a Linked List

In this article, we are going to study about the logic behind the flattening of linked list and we also going to build a code in the C++ to flatten...

3 minutes read.

Time Complexity of Selection Sort in Data Structure

What is Time Complexity? The term “Time complexity” can be defined as the number of times executions made of a particular sequence of instructions and not the total amount of time...

3 minutes read.

Detect and Remove Loop in a Linked List

Create a function called detectAndRemovetheLoop() that verifies whether a given Linked List has a loop, eliminates the loop if it does, and returns true if it does. It returns false...

6 minutes read.

Find Bridges in a Graph

You have been given a graph. You have to find out the bridges in that graph. Graph may be connected or disconnected. You have to print vertices of particular edge...

4 minutes read.

Red Black Tree

Red Black Tree A red-black tree is referred as self-balancing binary search tree. The tree was invented by Rudolf Bayer in 1972. In red-black, each node stores an extra bit that...

8 minutes read.

Convert a Binary Tree into a Binary Search Tree

Implementation #include <stdio.h>   #include <stdlib.h>       //creating a node of the binary tree.  struct __nod{       int record;       struct __nod *Lft;       struct __nod *Rt;   };       // presenting the root of the binary tree.   struct...

5 minutes read.

Intersection Point in Y Shaped Linked Lists in Java

Intersection Point in Y Shaped Linked Lists in Java In this article, we are going to see how to find the intersection point in a Y-shaped linked list. Method 1: We need to...

4 minutes read.

Introduction and Implementation of Bloom Filter

It often happens with many of us that when we create an account on some applications like Github, it shows us that the username already exists. You can add some...

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

Difference between B-tree and Binary Tree

What is B-TREE? The nodes of B-tree are sorted during in-order traversal, and it is called self-balancing tree. A node in a B-tree can have more than two offspring, in contrast...

3 minutes read.

Preorder Traversal of Binary Trees

In general, Stack, Array, Queue, and other linear data structures only have one way to traverse the data. However, there are numerous ways to traverse through the data in a hierarchical...

3 minutes read.