A height balanced binary tree is a binary tree in which the height of the left subtree and right subtree of any node does not differ by more than 1 and both the left and right subtree are also height balanced.
In this article, we will look into methods how to determine if given Binary trees are height-balanced
Examples: The tree on the left is a height balanced binary tree. Whereas the tree on the right is not a height balanced tree. Because the left subtree of the root has a height which is 2 more than the height of the right subtree.
Â
Naive Approach: To check if a tree is height-balanced:
Get the height of left and right subtrees using dfs traversal. Return true if the difference between heights is not more than 1 and left and right subtrees are balanced, otherwise return false.Â
Below is the implementation of the above approach.
C++
/* CPP program to check ifa tree is height-balanced or not */Â
#include <bits/stdc++.h>using namespace std;Â
/* A binary tree node has data,pointer to left child anda pointer to right child */class Node {public:Â Â Â Â int data;Â Â Â Â Node* left;Â Â Â Â Node* right;Â Â Â Â Node(int d)Â Â Â Â {Â Â Â Â Â Â Â Â int data = d;Â Â Â Â Â Â Â Â left = right = NULL;Â Â Â Â }};Â
// Function to calculate the height of a treeint height(Node* node){    // base case tree is empty    if (node == NULL)        return 0;Â
    // If tree is not empty then    // height = 1 + max of left height    // and right heights    return 1 + max(height(node->left), height(node->right));}Â
// Returns true if binary tree// with root as root is height-balancedbool isBalanced(Node* root){    // for height of left subtree    int lh;Â
    // for height of right subtree    int rh;Â
    // If tree is empty then return true    if (root == NULL)        return 1;Â
    // Get the height of left and right sub trees    lh = height(root->left);    rh = height(root->right);Â
    if (abs(lh - rh) <= 1 && isBalanced(root->left)        && isBalanced(root->right))        return 1;Â
    // If we reach here then tree is not height-balanced    return 0;}Â
// Driver codeint main(){Â Â Â Â Node* root = new Node(1);Â Â Â Â root->left = new Node(2);Â Â Â Â root->right = new Node(3);Â Â Â Â root->left->left = new Node(4);Â Â Â Â root->left->right = new Node(5);Â Â Â Â root->left->left->left = new Node(8);Â
    if (isBalanced(root))        cout << "Tree is balanced";    else        cout << "Tree is not balanced";    return 0;}Â
// This code is contributed by rathbhupendra |
C
/* C program to check if a tree is height-balanced or not */#include <stdio.h>#include <stdlib.h>#define bool intÂ
/* A binary tree node has data, pointer to left child   and a pointer to right child */struct node {    int data;    struct node* left;    struct node* right;};Â
/* Returns the height of a binary tree */int height(struct node* node);Â
/* Returns true if binary tree with root as root is * height-balanced */bool isBalanced(struct node* root){    /* for height of left subtree */    int lh;Â
    /* for height of right subtree */    int rh;Â
    /* If tree is empty then return true */    if (root == NULL)        return 1;Â
    /* Get the height of left and right sub trees */    lh = height(root->left);    rh = height(root->right);Â
    if (abs(lh - rh) <= 1 && isBalanced(root->left)        && isBalanced(root->right))        return 1;Â
    /* If we reach here then tree is not height-balanced */    return 0;}Â
/* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */Â
/* returns 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 nodes along the longest path from the root   node down to the farthest leaf node.*/int height(struct node* node){    /* base case tree is empty */    if (node == NULL)        return 0;Â
    /* If tree is not empty then height = 1 + max of left      height and right heights */    return 1 + max(height(node->left), height(node->right));}Â
/* Helper function that allocates a new node with the   given data and NULL left and right pointers. */struct node* newNode(int data){    struct node* node        = (struct node*)malloc(sizeof(struct node));    node->data = data;    node->left = NULL;    node->right = NULL;Â
    return (node);}Â
// Driver codeint main(){Â Â Â Â struct node* root = newNode(1);Â Â Â Â root->left = newNode(2);Â Â Â Â root->right = newNode(3);Â Â Â Â root->left->left = newNode(4);Â Â Â Â root->left->right = newNode(5);Â Â Â Â root->left->left->left = newNode(8);Â
    if (isBalanced(root))        printf("Tree is balanced");    else        printf("Tree is not balanced");Â
    getchar();    return 0;} |
Java
/* Java program to determine if binary tree is   height balanced or not */Â
/* A binary tree node has data, pointer to left child,   and a pointer to right child */class Node {    int data;    Node left, right;    Node(int d)    {        data = d;        left = right = null;    }}Â
class BinaryTree {Â Â Â Â Node root;Â
    /* Returns true if binary tree with root as root is     * height-balanced */    boolean isBalanced(Node node)    {        int lh; /* for height of left subtree */Â
        int rh; /* for height of right subtree */Â
        /* If tree is empty then return true */        if (node == null)            return true;Â
        /* Get the height of left and right sub trees */        lh = height(node.left);        rh = height(node.right);Â
        if (Math.abs(lh - rh) <= 1 && isBalanced(node.left)            && isBalanced(node.right))            return true;Â
        /* If we reach here then tree is not height-balanced         */        return false;    }Â
    /* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */    /* The function Compute the "height" of a tree. Height       is the number of nodes along the longest path from       the root node down to the farthest leaf node.*/    int height(Node node)    {        /* base case tree is empty */        if (node == null)            return 0;Â
        /* If tree is not empty then height = 1 + max of         left height and right heights */        return 1            + Math.max(height(node.left),                       height(node.right));    }Â
    public static void main(String args[])    {        BinaryTree tree = new BinaryTree();        tree.root = new Node(1);        tree.root.left = new Node(2);        tree.root.right = new Node(3);        tree.root.left.left = new Node(4);        tree.root.left.right = new Node(5);        tree.root.left.left.left = new Node(8);Â
        if (tree.isBalanced(tree.root))            System.out.println("Tree is balanced");        else            System.out.println("Tree is not balanced");    }}Â
// This code has been contributed by Mayank// Jaiswal(mayank_24) |
Python3
"""Python3 program to check if a tree is height-balanced"""# A binary tree NodeÂ
Â
class Node:    # Constructor to create a new Node    def __init__(self, data):        self.data = data        self.left = None        self.right = NoneÂ
# function to find height of binary treeÂ
Â
def height(root):Â
    # base condition when binary tree is empty    if root is None:        return 0    return max(height(root.left), height(root.right)) + 1Â
# function to check if tree is height-balanced or notÂ
Â
def isBalanced(root):Â
    # Base condition    if root is None:        return TrueÂ
    # for left and right subtree height    lh = height(root.left)    rh = height(root.right)Â
    # allowed values for (lh - rh) are 1, -1, 0    if (abs(lh - rh) <= 1) and isBalanced(            root.left) is True and isBalanced(root.right) is True:        return TrueÂ
    # if we reach here means tree is not    # height-balanced tree    return FalseÂ
Â
# Driver function to test the above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.left.left.left = Node(8)if isBalanced(root):Â Â Â Â print("Tree is balanced")else:Â Â Â Â print("Tree is not balanced")Â
# This code is contributed by Shweta Singh |
C#
using System;Â
/* C# program to determine if binary tree isheight balanced or not */Â
/* A binary tree node has data, pointer to left child,and a pointer to right child */public class Node {Â Â Â Â public int data;Â Â Â Â public Node left, right;Â Â Â Â public Node(int d)Â Â Â Â {Â Â Â Â Â Â Â Â data = d;Â Â Â Â Â Â Â Â left = right = null;Â Â Â Â }}Â
public class BinaryTree {Â Â Â Â public Node root;Â
    /* Returns true if binary tree with root as    root is height-balanced */    public virtual bool isBalanced(Node node)    {        int lh; // for height of left subtreeÂ
        int rh; // for height of right subtreeÂ
        /* If tree is empty then return true */        if (node == null) {            return true;        }Â
        /* Get the height of left and right sub trees */        lh = height(node.left);        rh = height(node.right);Â
        if (Math.Abs(lh - rh) <= 1 && isBalanced(node.left)            && isBalanced(node.right)) {            return true;        }Â
        /* If we reach here then tree is not height-balanced         */        return false;    }Â
    /* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */    /* The function Compute the "height" of a tree. Height       is the number of nodes along the longest path from       the root node down to the farthest leaf node.*/    public virtual int height(Node node)    {        /* base case tree is empty */        if (node == null) {            return 0;        }Â
        /* If tree is not empty then height = 1 + max of        left height and right heights */        return 1            + Math.Max(height(node.left),                       height(node.right));    }Â
    public static void Main(string[] args)    {        BinaryTree tree = new BinaryTree();        tree.root = new Node(1);        tree.root.left = new Node(2);        tree.root.right = new Node(3);        tree.root.left.left = new Node(4);        tree.root.left.right = new Node(5);        tree.root.left.left.left = new Node(8);Â
        if (tree.isBalanced(tree.root)) {            Console.WriteLine("Tree is balanced");        }        else {            Console.WriteLine("Tree is not balanced");        }    }}Â
// This code is contributed by Shrikant13 |
Javascript
<script>Â
// JavaScript program to check if a tree is height-balanced//Â A binary tree NodeÂ
class Node{    // Constructor to create a new Node    constructor(data){        this.data = data        this.left = null        this.right = null    }}Â
// function to find height of binary treefunction height(root){         // base condition when binary tree is empty    if(root == null)        return 0    return Math.max(height(root.left), height(root.right)) + 1}Â
// function to check if tree is height-balanced or notfunction isBalanced(root){         // Base condition    if(root == null)        return trueÂ
    // for left and right subtree height    let lh = height(root.left)    let rh = height(root.right)Â
    // allowed values for (lh - rh) are 1, -1, 0    if (Math.abs(lh - rh) <= 1 && isBalanced(    root.left)== true && isBalanced( root.right) == true)        return trueÂ
    // if we reach here means tree is not     // height-balanced tree    return false}Â
// Driver function to test the above functionlet root = new Node(1)root.left = new Node(2)root.right = new Node(3)root.left.left = new Node(4)root.left.right = new Node(5)root.left.left.left = new Node(8)if(isBalanced(root))    document.write("Tree is balanced","</br>")else    document.write("Tree is not balanced","</br>")Â
// This code is contributed by ShinjanPatraÂ
</script> |
Tree is not balanced
Time Complexity: O(n^2) in case of full binary tree.
Auxiliary Space: O(n) space for call stack since using recursion
Efficient implementation: Above implementation can be optimized byÂ
Calculating the height in the same recursion rather than calling a height() function separately.Â
- For each node make two recursion calls – one for left subtree and the other for the right subtree.Â
- Based on the heights returned from the recursion calls, decide if the subtree whose root is the current node is height-balanced or not.Â
- If it is balanced then return the height of that subtree. Otherwise, return -1 to denote that the subtree is not height-balanced.
Below is the implementation of the above approach.
C++
// C++ code to implement the approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Structure of a tree nodestruct Node {Â Â Â Â int key;Â Â Â Â struct Node* left;Â Â Â Â struct Node* right;Â Â Â Â Node(int k)Â Â Â Â {Â Â Â Â Â Â Â Â key = k;Â Â Â Â Â Â Â Â left = right = NULL;Â Â Â Â }};Â
// Function to check if tree is height balancedint isBalanced(Node* root){Â Â Â Â if (root == NULL)Â Â Â Â Â Â Â Â return 0;Â Â Â Â int lh = isBalanced(root->left);Â Â Â Â if (lh == -1)Â Â Â Â Â Â Â Â return -1;Â Â Â Â int rh = isBalanced(root->right);Â Â Â Â if (rh == -1)Â Â Â Â Â Â Â Â return -1;Â
    if (abs(lh - rh) > 1)        return -1;    else        return max(lh, rh) + 1;}Â
// Driver codeint main(){Â Â Â Â Node* root = new Node(10);Â Â Â Â root->left = new Node(5);Â Â Â Â root->right = new Node(30);Â Â Â Â root->right->left = new Node(15);Â Â Â Â root->right->right = new Node(20);Â
    if (isBalanced(root) > 0)        cout << "Balanced";    else        cout << "Not Balanced";    return 0;} |
C
// C program to check if a tree is height-balanced or not */#include <stdio.h>#include <stdlib.h>#define bool intÂ
// Structure of a tree nodestruct node {Â Â Â Â int data;Â Â Â Â struct node* left;Â Â Â Â struct node* right;};Â
// Function to create a new tree Nodestruct node* newNode(int data){    struct node* node        = (struct node*)malloc(sizeof(struct node));    node->data = data;    node->left = NULL;    node->right = NULL;Â
    return (node);}Â
// Functio to check if tree is height balancedint isBalanced(struct node* root){Â Â Â Â if (root == NULL)Â Â Â Â Â Â Â Â return 0;Â Â Â Â int lh = isBalanced(root->left);Â Â Â Â if (lh == -1)Â Â Â Â Â Â Â Â return -1;Â Â Â Â int rh = isBalanced(root->right);Â Â Â Â if (rh == -1)Â Â Â Â Â Â Â Â return -1;Â
    if (abs(lh - rh) > 1)        return -1;    else        return lh > rh ? lh + 1 : rh + 1;}Â
// Driver codeint main(){Â Â Â Â int height = 0;Â
    struct node* root = newNode(10);    root->left = newNode(5);    root->right = newNode(30);    root->right->left = newNode(15);    root->right->right = newNode(20);Â
    if (isBalanced(root) > 0)        printf("Balanced");    else        printf("Not Balanced");Â
    getchar();    return 0;} |
Java
// Java code to implement the approachÂ
import java.io.*;import java.lang.*;import java.util.*;Â
// Class to define the tree nodeclass Node {Â Â Â Â int key;Â Â Â Â Node left;Â Â Â Â Node right;Â Â Â Â Node(int k)Â Â Â Â {Â Â Â Â Â Â Â Â key = k;Â Â Â Â Â Â Â Â left = right = null;Â Â Â Â }}Â
class GFG {Â
    // Driver code    public static void main(String args[])    {        Node root = new Node(10);        root.left = new Node(5);        root.right = new Node(30);        root.right.left = new Node(15);        root.right.right = new Node(20);Â
        if (isBalanced(root) > 0)            System.out.print("Balanced");        else            System.out.print("Not Balanced");    }Â
    // Function to check if tree is height balanced    public static int isBalanced(Node root)    {        if (root == null)            return 0;        int lh = isBalanced(root.left);        if (lh == -1)            return -1;        int rh = isBalanced(root.right);        if (rh == -1)            return -1;Â
        if (Math.abs(lh - rh) > 1)            return -1;        else            return Math.max(lh, rh) + 1;    }} |
Python3
"""Python3 program to check if a tree is height-balanced"""# A binary tree NodeÂ
Â
class Node:Â
    # Constructor to create a new Node    def __init__(self, data):        self.data = data        self.left = None        self.right = NoneÂ
# Function to check if tree is height-balanced or notÂ
Â
def isBalanced(root):Â
    # Base condition    if root is None:        return TrueÂ
    # Compute height of left subtree    lh = isBalanced(root.left)Â
    # If left subtree is not balanced,    # return 0    if lh == 0:        return 0Â
    # Do same thing for the right subtree    rh = isBalanced(root.right)    if rh == 0:        return 0Â
    # Allowed values for (lh - rh) are 1, -1, 0    if (abs(lh - rh) > 1):        return 0Â
    # If we reach here means tree is    # height-balanced tree, return height    # in this case    else:        return max(lh, rh) + 1Â
Â
# Driver codeif __name__ == '__main__':Â Â Â Â root = Node(10)Â Â Â Â root.left = Node(5)Â Â Â Â root.right = Node(30)Â Â Â Â root.right.left = Node(15)Â Â Â Â root.right.right = Node(20)Â Â Â Â if (isBalanced(root) == 0):Â Â Â Â Â Â Â Â print("Not Balanced")Â Â Â Â else:Â Â Â Â Â Â Â Â print("Balanced")Â
# This code is contributed by Shweta Singh |
C#
// C# code to implement the approachÂ
using System;Â
// Class to define a binary tree nodepublic class Node {Â Â Â Â public int data;Â Â Â Â public Node left, right;Â
    public Node(int d)    {        data = d;        left = right = null;    }}Â
public class BinaryTree {Â Â Â Â public Node root;Â
    // Function to check if tree is height balanced    public virtual int isBalanced(Node root)    {        if (root == null)            return 0;        int lh = isBalanced(root.left);        if (lh == -1)            return -1;        int rh = isBalanced(root.right);        if (rh == -1)            return -1;Â
        if (lh > rh + 1 || rh > lh + 1)            return -1;        else            return Math.Max(lh, rh) + 1;    }Â
    // Driver code    public static void Main(string[] args)    {        BinaryTree tree = new BinaryTree();        tree.root = new Node(10);        tree.root.left = new Node(5);        tree.root.right = new Node(30);        tree.root.right.left = new Node(15);        tree.root.right.right = new Node(20);Â
        if (tree.isBalanced(tree.root) > 0) {            Console.WriteLine("Balanced");        }        else {            Console.WriteLine("Not Balanced");        }    }}Â
// This code is contributed by Shrikant13 |
Javascript
<script>Â
// JavaScript program to check if Binary tree is height-balancedÂ
// Class to define a binary tree nodeclass Node{      // Constructor to create node of    // binary tree    constructor(data){        this.data = data        this.left = this.right = null    }}Â
// Function to check if the tree is height balancedfunction isBalanced(root){Â Â Â Â if (root == null)Â Â Â Â Â Â Â Â Â Â Â Â return 0;Â Â Â Â Â Â Â Â int lh = isBalanced(root.left);Â Â Â Â Â Â Â Â if (lh == -1)Â Â Â Â Â Â Â Â Â Â Â Â return -1;Â Â Â Â Â Â Â Â int rh = isBalanced(root.right);Â Â Â Â Â Â Â Â if (rh == -1)Â Â Â Â Â Â Â Â Â Â Â Â return -1;Â
        if (Math.abs(lh - rh) > 1)            return -1;        else            return Math.max(lh, rh) + 1;}Â
// Driver codelet root = new Node(10)root.left = new Node(5)root.right = new Node(30)root.right.left = new Node(15)root.right.right = new Node(20)Â
if(isBalanced(root) > 0)    document.write('Balanced',"</br>")else    document.write('Not Balanced',"</br>")Â
// This code is contributed by shinjanpatra</script> |
Balanced
Time Complexity: O(n)Â
- Because we are only one dfs call and utilizing the height returned from that to determine the height balance, it is performing the task in linear time.
Auxiliary Space: O(n)
Using Pair:
The idea is simple instead of calling two recursive function ‘isBalanced’ and ‘height’ we can use a pair in which first value will represent that if any subtree is balanced or not and second value will represent the height of the every subtree in this way we can easily find that if tree is balanced or not.
Follow the steps below to implement the above idea:
- Define a helper function isBalancedfast that takes a root node as input and returns a pair of boolean and integer values representing whether the tree rooted at the given node is balanced and its height, respectively.
- Define the base case for the recursion: if the root node is NULL, return a pair with first set to true and second set to 0.
- Recursively call isBalancedfast on the left and right subtrees of the current node.
- Retrieve the boolean and integer values from the returned pairs and set them to leftAns, rightAns, leftHeight, and rightHeight.
- Calculate the height of the current node by taking the maximum height of its left and right subtrees and adding 1.
- Check if the absolute difference between the heights of the left and right subtrees is less than or equal to 1. If so, set diff to true; otherwise, set it to false.
- Set ans.first to true if leftAns, rightAns, and diff are all true; otherwise, set it to false.
- Set ans.second to the height of the current node.
- Return ans.
- Define a public function isBalanced that takes a root node as input and calls the isBalancedfast helper function on the root node.
- Return the first element of the pair returned by the isBalancedfast function. This represents whether the entire binary tree is balanced or not.
Below is the implementation of the above approach:
C++
//C++ code to implement the above approach#include <bits/stdc++.h>// using the standard namespaceusing namespace std;Â
// defining the structure for tree nodesstruct Node {Â Â Â Â int val;Â Â Â Â Node *left, *right;Â Â Â Â Node(int v)Â Â Â Â Â Â Â Â : val(v)Â Â Â Â Â Â Â Â , left(nullptr)Â Â Â Â Â Â Â Â , right(nullptr)Â Â Â Â {Â Â Â Â }};Â
// defining the Solution class to check if a binary tree is// balancedclass Solution {    // helper function to determine if a binary tree is    // balanced    pair<bool, int> isBalancedfast(Node* root)    {        // base case: if root is null, the tree is balanced        // and has height 0        if (root == NULL) {            pair<bool, int> p = make_pair(true, 0);            return p;        }        // recursively call isBalancedfast function on left        // and right subtrees        pair<int, int> left = isBalancedfast(root->left);        pair<int, int> right = isBalancedfast(root->right);Â
        // retrieve whether left and right subtrees are        // balanced        bool leftAns = left.first;        bool rightAns = right.first;Â
        // check the difference in heights of left and right        // subtrees        bool diff = abs(left.second - right.second) <= 1;Â
        // create a pair to store the answer (whether the        // tree is balanced) and its height        pair<bool, int> ans;        // set the height of the current node        ans.second = max(left.second, right.second) + 1;        // if both subtrees are balanced and their heights        // differ by at most 1, the tree is balanced        if (leftAns && rightAns && diff) {            ans.first = true;        }        // otherwise, the tree is not balanced        else {            ans.first = false;        }        return ans;    }Â
public:    // Function to check whether a binary tree is balanced    // or not.    bool isBalanced(Node* root)    {        return isBalancedfast(root).first;    }};//Driver Codeint main(){    // create a binary tree    Node* root = new Node(1);    root->left = new Node(2);    root->right = new Node(3);    root->left->left = new Node(4);    root->left->right = new Node(5);    root->left->left->left = new Node(8);Â
    // create an object of the Solution class    Solution obj;    // check if the binary tree is balanced using the    // isBalanced function    if (obj.isBalanced(root)) {        cout << "The given binary tree is balanced."             << endl;    }    else {        cout << "The given binary tree is not balanced."             << endl;    }Â
    return 0;}//This code is contributed by Veerendra_Singh_Rajpoot |
C#
using System;Â
// defining the structure for tree nodespublic class Node {Â Â Â Â public int val;Â Â Â Â public Node left;Â Â Â Â public Node right;Â Â Â Â public Node(int v)Â Â Â Â {Â Â Â Â Â Â Â Â val = v;Â Â Â Â Â Â Â Â left = null;Â Â Â Â Â Â Â Â right = null;Â Â Â Â }}Â
// defining the Solution class to check// if a binary tree is balancedpublic class Solution {Â
    // helper function to determine if a    // binary tree is balanced    public(bool, int) IsBalancedfast(Node root)    {        // base case: if root is null,        // the tree is balanced        // and has height 0        if (root == null) {            return (true, 0);        }Â
        // recursively call IsBalancedfas        // t function on left & right subtrees        var left = IsBalancedfast(root.left);        var right = IsBalancedfast(root.right);Â
        // retrieve whether left and right        // subtrees are balanced        bool leftAns = left.Item1;        bool rightAns = right.Item1;Â
        // check the difference in heights of        // left and right subtrees        bool diff = Math.Abs(left.Item2 - right.Item2) <= 1;Â
        // if both subtrees are balanced        // and their heights differ by at most        // 1, the tree is balanced        if (leftAns && rightAns && diff) {            return (true,                    Math.Max(left.Item2, right.Item2) + 1);        }        // otherwise, the tree is not balanced        else {            return (false, 0);        }    }    // Function to check whether a binary    // tree is balanced or not.    public bool IsBalanced(Node root)    {        return IsBalancedfast(root).Item1;    }}Â
// Driver Codepublic class Program {    public static void Main(string[] args)    {        // create a binary tree        Node root = new Node(1);        root.left = new Node(2);        root.right = new Node(3);        root.left.left = new Node(4);        root.left.right = new Node(5);        root.left.left.left = new Node(8);Â
        // create an object of Solution class        Solution obj = new Solution();Â
        // check if the binary tree is        // balanced using the        // IsBalanced function        if (obj.IsBalanced(root)) {            Console.WriteLine(                "The given binary tree is balanced.");        }        else {            Console.WriteLine(                "The given binary tree is not balanced.");        }    }} |
Java
// defining the structure for tree nodesclass Node {Â Â Â Â int val;Â Â Â Â Node left, right;Â
    public Node(int v) {        val = v;        left = null;        right = null;    }}Â
// defining the Solution class to check if a binary tree is balancedclass Solution {    // helper function to determine if a binary tree is balanced    private Pair<Boolean, Integer> isBalancedfast(Node root) {        // base case: if root is null, the tree is balanced and has height 0        if (root == null) {            Pair<Boolean, Integer> p = new Pair<>(true, 0);            return p;        }Â
        // recursively call isBalancedfast function on left and right subtrees        Pair<Boolean, Integer> left = isBalancedfast(root.left);        Pair<Boolean, Integer> right = isBalancedfast(root.right);Â
        // retrieve whether left and right subtrees are balanced        boolean leftAns = left.first;        boolean rightAns = right.first;Â
        // check the difference in heights of left and right subtrees        boolean diff = Math.abs(left.second - right.second) <= 1;Â
        // create a pair to store the answer (whether the tree is balanced) and its height        Pair<Boolean, Integer> ans = new Pair<>(false, Math.max(left.second, right.second) + 1);Â
        // if both subtrees are balanced and their heights differ by at most 1, the tree is balanced        if (leftAns && rightAns && diff) {            ans = new Pair<>(true, Math.max(left.second, right.second) + 1);        }Â
        return ans;    }Â
    // Function to check whether a binary tree is balanced or not.    public boolean isBalanced(Node root) {        return isBalancedfast(root).first;    }}Â
// Driver Codepublic class Main {    public static void main(String[] args) {        // create a binary tree        Node root = new Node(1);        root.left = new Node(2);        root.right = new Node(3);        root.left.left = new Node(4);        root.left.right = new Node(5);        root.left.left.left = new Node(8);Â
        // create an object of the Solution class        Solution obj = new Solution();Â
        // check if the binary tree is balanced using the isBalanced function        if (obj.isBalanced(root)) {            System.out.println("The given binary tree is balanced.");        } else {            System.out.println("The given binary tree is not balanced.");        }    }} |
Python3
# defining the structure for tree nodesclass Node:    def __init__(self, val):        self.val = val        self.left = None        self.right = NoneÂ
# defining the Solution class to check if a binary tree is# balancedclass Solution:    # helper function to determine if a binary tree is    # balanced    def isBalancedfast(self, root):        # base case: if root is None, the tree is balanced        # and has height 0        if root is None:            return True, 0        # recursively call isBalancedfast function on left        # and right subtrees        left = self.isBalancedfast(root.left)        right = self.isBalancedfast(root.right)Â
        # retrieve whether left and right subtrees are        # balanced        leftAns = left[0]        rightAns = right[0]Â
        # check the difference in heights of left and right        # subtrees        diff = abs(left[1] - right[1]) <= 1Â
        # set the height of the current node        height = max(left[1], right[1]) + 1        # if both subtrees are balanced and their heights        # differ by at most 1, the tree is balanced        if leftAns and rightAns and diff:            return True, height        # otherwise, the tree is not balanced        else:            return False, heightÂ
    # Function to check whether a binary tree is balanced    # or not.    def isBalanced(self, root):        return self.isBalancedfast(root)[0]Â
# create a binary treeroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.left.left.left = Node(8)Â
# create an object of the Solution classobj = Solution()# check if the binary tree is balanced using the# isBalanced functionif obj.isBalanced(root):Â Â Â Â print("The given binary tree is balanced.")else:Â Â Â Â print("The given binary tree is not balanced.") |
Javascript
// defining the structure for tree nodesclass Node {constructor(val) {this.val = val;this.left = null;this.right = null;}}Â
// defining the Solution class to check if a binary tree is// balancedclass Solution {Â
// helper function to determine if a binary tree is// balancedisBalancedfast(root) {Â
// base case: if root is null, the tree is balanced// and has height 0if (root == null) {return [true, 0];}Â
// recursively call isBalancedfast function on left// and right subtreeslet left = this.isBalancedfast(root.left);let right = this.isBalancedfast(root.right);Â
    // retrieve whether left and right subtrees are    // balanced    let leftAns = left[0];    let rightAns = right[0];Â
    // check the difference in heights of left and right    // subtrees    let diff = Math.abs(left[1] - right[1]) <= 1;Â
    // create an array to store the answer (whether the    // tree is balanced) and its height    let ans = [];         // set the height of the current node    ans[1] = Math.max(left[1], right[1]) + 1;         // if both subtrees are balanced and their heights    // differ by at most 1, the tree is balanced    if (leftAns && rightAns && diff) {        ans[0] = true;    }    // otherwise, the tree is not balanced    else {        ans[0] = false;    }    return ans;}Â
// Function to check whether a binary tree is balanced// or not.isBalanced(root) {Â Â Â Â return this.isBalancedfast(root)[0];}}Â
// create a binary treelet root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.left.left.left = new Node(8);Â
// create an object of the Solution classlet obj = new Solution();Â
// check if the binary tree is balanced using the// isBalanced functionif (obj.isBalanced(root)) {console.log("The given binary tree is balanced.");}else {console.log("The given binary tree is not balanced.");} |
The given binary tree is not balanced.
Time Complexity: O(N) , where N is the number of nodes present in the tree, This is Because every node of the tree is visited only ones.
Auxiliary Space: O(H) , where h is the height of the binary tree.
Asked in: Amazon, Belzabar, Goldman Sachs, InMobi, Intel, Microsoft, Paytm, Synopsys, Walmart, Zillious
Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

