×

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

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.

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.

Recaman’s Sequence

Recamán's succession repeat connection in arithmetic and software engineering. Since its components are obviously connected with the past components, they are as often as possible characterized utilizing recursion. It takes its...

4 minutes read.

Doubly Linked List

Doubly Linked List Doubly linked list is another kind of Linked list. Doubly linked list contains two pointers for navigation. In this, we can traverse the list in both directions, either...

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

Binary Tree to Doubly Linked List

Binary Tree to Doubly Linked List This article will explain how to convert the given binary tree into a Doubly Linked List. The left and right pointers in tree nodes are...

2 minutes read.

Minimum Spanning Tree

Before getting to know about the minimum spanning tree, we should first discuss about what is a spanning tree. A spanning tree is basically a sub or minimized graph that...

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.

Top view of binary tree

We know that a binary tree is a kind of tree that helps us organize our tree and that it is a kind of non-linear info structure that at least...

4 minutes read.

DFS (Depth-first search) Algorithm: Data Structure

What is DFS (Depth-first search)? The depth first search is a graph traversal algorithm. The idea behind this algorithm is backtracking and it is a kind of recursive algorithm. In the...

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.

Linear vs Binary Search: Data Structure

Difference Between Linear and Binary Search What is Linear Search? A linear search also referred as a sequential search. It is a way to find an element within a list and it...

3 minutes read.

Array vs Linked List: Data Structure

Data structure: Difference Between Array and Linked List What is Array? An array is a linear data structure that can store similar data items for further processing. The similar data items...

3 minutes read.

Selection Sort

In each iteration of the selection sort algorithm, the smallest item from an unsorted list is chosen and placed at the top of the unsorted list. Algorithm of Selection Sorting In order...

3 minutes read.

Delete a Node without head pointer from the linked list

Delete a Node without head pointer from the linked list This article will explain how to delete a node without a head pointer from the linked list. We have given a...

2 minutes read.

Diameter of a Binary Tree

Implementation We will now witness the implementation of the diameter of a binary tree. // Creating a recursive and challenging C program that will help us determine the diameter of a binary...

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.

Application of 2D array - Sparse Matrix

2D Arrays Application - Sparse Matrix A matrix is a two-dimensional data item consisting of m rows and n columns, with a total of m x n values. A sparse matrix...

7 minutes read.

Strictly binary tree in Data Structures?

What is a strictly Binary Tree in Data Structures? There are various kinds of binary trees that we know exist in data structures, and they all have their purposes. In this...

4 minutes read.

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

4 minutes read.