Check if a given Binary Tree is height balanced like a Red-Black Tree in C++

C++Server Side ProgrammingProgramming

Concept

With respect of a Red-Black Tree, the largest height of a node is at most double the minimum height.For a given Binary Search Tree, we need to verify for following property.

With respect of every node, length of the longest leaf to node path has not more than double the nodes on shortest path from node to leaf.

Examples

13    41
\    / \
15  11 101
\   /    \
17 61 151

Above tree cannot be a Red-Black Tree Above tree can be Red-Black Tree with any color assignment

Max height of 13 is 1

Min height of 13 is 3

   11
  / \
 6   101
 /    \
51    151
/
41

Above tree can also be Red-Black Tree

In this case,expected time complexity is O(n). The tree should be visited at-most once in the solution.

Method

With respect of every node, we require to obtain the largest and smallest heights and compare them. The concept is to visit the tree and for every node verify if it’s balanced. Our need is to write a recursive function that returns three things, a boolean value to indicate the tree is balanced or not, smallest height and largest height. For returning multiple values, we can either apply a structure or pass variables by reference.Passing maxh and minhby reference is performed so that the values can be applied in parent calls.

Example

 Live Demo

/* This program to check whether a given Binary Tree is balanced like a Red-Black Tree or not */
#include <bits/stdc++.h>
using namespace std;
struct Node1{
   int key;
   Node1 *left, *right;
};
Node1* newNode(int key){
   Node1* node1 = new Node1;
   node1->key = key;
   node1->left = node1->right = NULL;
   return (node1);
}
bool isBalancedUtil(Node1 *root, int &maxh1, int &minh1){
   if (root == NULL){
      maxh1 = minh1 = 0;
      return true;
   }
   int lmxh1, lmnh1;
   int rmxh1, rmnh1;
   if (isBalancedUtil(root->left, lmxh1, lmnh1) == false)
      return false;
   if (isBalancedUtil(root->right, rmxh1, rmnh1) == false)
      return false;
   maxh1 = max(lmxh1, rmxh1) + 1;
   minh1 = min(lmnh1, rmnh1) + 1;
   if (maxh1 <= 2*minh1)
      return true;
   return false;
}
bool isBalanced(Node1 *root){
   int maxh1, minh1;
   return isBalancedUtil(root, maxh1, minh1);
}
/* Driver program to test above functions*/
int main(){
   Node1 * root = newNode(11);
   root->left = newNode(6);
   root->right = newNode(101);
   root->right->left = newNode(51);
   root->right->right = newNode(151);
   root->right->left->left = newNode(41);
   isBalanced(root)? cout << "Balanced" : cout << "Not Balanced";
   return 0;
}

Output

Balanced
raja
Published on 23-Jul-2020 07:39:38
Advertisements