×

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 value, a given pointer to the left and right child. 
*/
class __Nod {
public:
	int record;
	__Nod* Lft;
	__Nod* Rt;
	__Nod(int d)
	{
		int record = d;
		Lft = Rt = NILL;
	}
};


// creating a function that will help us calculate the tree's height. 
int height(__Nod* __Nod)
{
	// the tree is vacant in the basic case given.
	if (__Nod == NILL)
		return 0;


	// In case the given tree is not vacant or empty, then we have height = 1 + maximum of the tree's left and right height. 
	return 1 + max(height(__Nod->Lft), height(__Nod->Rt));
}


// We must return the true value if the tree has a height-balanced root. 
bool isBalanced(__Nod* root)
{
	// to get the height of the left subtree.
	int lh;


	// to get the height of the right subtree.
	int rh;


	// if the given tree appears vacant, we must return the value.
	if (root == NILL)
		return 1;


	// we have to get the height of the left and right subtrees.
	lh = height(root->Lft);
	rh = height(root->Rt);


	if (abs(lh - rh) <= 1 && isBalanced(root->Lft)
		&& isBalanced(root->Rt))
		return 1;


	// If this case arrives, then the given tree happens not to be height-balanced. 
	return 0;
}


// writing the main 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);
	root->Lft->Lft->Lft = new __Nod(8);


	if (isBalanced(root))
		cout << "Tree is balanced";
	else
		cout << "Tree is not balanced";
	return 0;
}

Output:

Given a Binary Tree, Check If It's Balanced

Example 2)

/*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;


// writing the structure of the node of the tree.
struct __Nod {
	int key;
	struct __Nod* Lft;
	struct __Nod* Rt;
	__Nod(int k)
	{
		key = k;
		Lft = Rt = NILL;
	}
};
// creating a function that will help us in checking whether the given tree is height-balanced or not. 
int isBalanced(__Nod* root)
{
	if (root == NILL)
		return 0;
	int lh = isBalanced(root->Lft);
	if (lh == -1)
		return -1;
	int rh = isBalanced(root->Rt);
	if (rh == -1)
		return -1;


	if (abs(lh - rh) > 1)
		return -1;
	else
		return max(lh, rh) + 1;
}


//writing the main code.


int main()
{
	__Nod* root = new __Nod(10);
	root->Lft = new __Nod(5);
	root->Rt = new __Nod(30);
	root->Rt->Lft = new __Nod(15);
	root->Rt->Rt = new __Nod(20);


	if (isBalanced(root))
		cout << "Balanced";
	else
		cout << "Not Balanced";
	return 0;
}

Output:

Given a Binary Tree, Check If It's Balanced

Example 3)

/*Creating a C program that will help us identify whether the given tree is height-balanced or not. 
*/
#include <stdio.h>
#include <stdlib.h>
#define bool int
/* A particular binary tree node consists of data with some value, a given pointer to the left and right child. 
*/
struct __Nod {
	int record;
	struct __Nod* Lft;
	struct __Nod* Rt;
};


/* Returns the height of a binary tree */
int height(struct __Nod* __Nod);
// We must return the true value if the tree has a height-balanced root. 
bool isBalanced(struct __Nod* root)
{
// to get the height of the left subtree.
	int lh;
// to get the height of the right subtree.
	int rh;
	// if the given tree appears vacant, we must return the value.
	if (root == NILL)
		return 1;
// we have to get the height of the left and right subtrees.
	lh = height(root->Lft);
	rh = height(root->Rt);


	if (abs(lh - rh) <= 1 && isBalanced(root->Lft)
		&& isBalanced(root->Rt))
		return 1;
// If this case arrives, then the given tree happens not to be height-balanced. 
	return 0;
}


/* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */


/* returns the maximum of two integers */
int max(int a, int b) { return (a >= b) ? a : b; }


/* The function Compute the "height" of a tree. Height is
the number of __Nods along the longest path from the root
__Nod down to the farthest leaf __Nod.*/
int height(struct __Nod* __Nod)
{
	// the tree is vacant in the basic case given.
	if (__Nod == NILL)
		return 0;


	// In case the given tree is not vacant or empty, then we have height = 1 + maximum of the tree's left and right height. 
	return 1 + max(height(__Nod->Lft), height(__Nod->Rt));
}


/* creating a new function called helper function which will help us allocate a new node with the given data set and put NILL values in the left and right pointers. 
*/
struct __Nod* new__Nod(int record)
{
	struct __Nod* __Nod
		= (struct __Nod*)malloc(sizeof(struct __Nod));
	__Nod->record = record;
	__Nod->Lft = NILL;
	__Nod->Rt = NILL;


	return (__Nod);
}


// writing the main code.
int main()
{
	struct __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);
	root->Lft->Lft->Lft = new__Nod(8);


	if (isBalanced(root))
		printf("Tree is balanced");
	else
		printf("Tree is not balanced");


	getchar();
	return 0;
}

Output:

Given a Binary Tree, Check If It's Balanced

Related Topics

Segregate Even and Odd nodes in a Linked List

Segregate even and odd nodes in a Linked List In this problem, we have given a linked list with integer numbers. We need to modify the given linked list in such...

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.

Sparse Matrix in Data Structure

Sparse Matrix The sparse matrix is a two-dimensional data object which is made by m rows and n columns, so we can say the number of data values in sparse matrix...

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

Given a Binary Tree Swap Nodes at K Height

Implementation // Writing a C++ program that will help us exchange the nodes.  #include<bits/stdc++.h> using namespace std; // Creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a function that will help...

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

Binary Tree Implementation Using Arrays

Implementation Converting a binary tree into a list of arrays is one interesting problem. Let us see that in depth. In this section, we will see the implementation of the binary Trees...

4 minutes read.

What is a Threaded Binary Tree?

When we consider those binary trees that are interlinked with each other, we do come across the fact that the fields present in there do consist of NULL values that...

3 minutes read.

How to get Better in Data Structures and Algorithms?

Introduction Data structures and algorithms are fundamental computer science concepts that store, organize, and process data efficiently. By understanding different data structures and algorithms and using them effectively, you can become...

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

Given a Binary Tree, Print the Pre-order Traversal in Recursive

Implementation #include <stdio.h> #include <stdlib.h>   /* Creating a binary tree node that consists of some data along with the pointer to the left and right child.  */ struct __nod {     int record;     struct...

4 minutes read.

Partitioning a linked list around a given value

Partitioning a linked list around a given value In this problem, we are given a linked list and a value k. We need to partition the given linked list so that...

3 minutes read.

Tree terminology in Data structures

Data structures The storage used to organize and store data is known as a data structure, and it is a method where data can be arranged on a computer to be...

6 minutes read.

Stack Using Linked List

In the linked list implementation of the stack, we use a linked list as the primitive data structure to create the stack. It is called the dynamic implementation of the...

6 minutes read.

Bucket Sort

Bucket Sort: In the sorting algorithm, we create buckets and put elements into them. We can apply some sorting algorithm (insertion sort) to sort the elements in each bucket. Finally,...

4 minutes read.

Optimal binary search tree using dynamic programming

Implementation // We are creating a presentation where we will present a recursive method of the optimal binary search tree problem.  #include <bits/stdc++.h> using namespace std; //creating a utility function that will help us...

9 minutes read.

Big O Notations

What is Big O Notation, and why is it important? "Big O notation is a mathematical notation that depicts a function's limiting behaviour when the input tends towards a certain value...

10 minutes read.

Red Black Tree vs AVL Tree: Data Structure

Difference Between Red Black Tree vs AVL Tree Red Black Tree: A red-black tree is referred as self-balancing binary search tree. In red-black, each node stores an extra bit that determines...

4 minutes read.

Data structure: Infix to Prefix Conversion

Infix to Prefix Conversion In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep...

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