The Wayback Machine - https://web.archive.org/web/20241225114251/https://www.geeksforgeeks.org/how-to-determine-if-a-binary-tree-is-balanced/
Open In App

Balanced Binary Tree or Not

Last Updated : 14 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

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.
 

Corner Cases : An empty binary tree (Root = NULL) and a Binary Tree with single node are considered balanced.

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 if
a tree is height-balanced or not */

#include <bits/stdc++.h>
using namespace std;

/* A binary tree node has data,
pointer to left child and
a 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 tree
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 + max(height(node->left), height(node->right));
}

// Returns true if binary tree
// with root as root is height-balanced
bool 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 code
int 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 code
int 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)
Python
"""
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 function
root = 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 is
height 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 tree
function 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 not
function 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 function
let 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>

Output
Tree is not balanced

Time Complexity: O(n^2)
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 node
struct Node {
    int key;
    struct Node* left;
    struct Node* right;
    Node(int k)
    {
        key = k;
        left = right = NULL;
    }
};

// Function to check if tree is height balanced
int isBalRec(Node* root)
{
    if (root == NULL)
        return 0;
    int lh = isBalRec(root->left);
    if (lh == -1)
        return -1;
    int rh = isBalRec(root->right);
    if (rh == -1)
        return -1;

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

bool isBalanced(Node *root) {
  return (isBalRec(root) > 0);
}

// Driver code
int 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))
        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 node
struct node {
    int data;
    struct node* left;
    struct node* right;
};

// Functio to check if tree is height balanced
int isBalRec(struct node* root)
{
    if (root == NULL)
        return 0;
    int lh = isBalRec(root->left);
    if (lh == -1)
        return -1;
    int rh = isBalRec(root->right);
    if (rh == -1)
        return -1;

    if (abs(lh - rh) > 1)
        return -1;
    else
        return lh > rh ? lh + 1 : rh + 1;
}

bool isBalanced(struct Node *root) {
   return (isBalRec(root) > 0);
}

// Function to create a new tree Node
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 code
int 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))
        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 node
class Node {
    int key;
    Node left;
    Node right;
    Node(int k)
    {
        key = k;
        left = right = null;
    }
}

class GFG {

    // 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;
    }
  
        // 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");
    }
}
Python
"""
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 code
if __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 node
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;

    // 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 node
class 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 balanced
function 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 code
let 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>

Output
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(h) where h is height of the binary tree.



Next Article

Similar Reads

three90RightbarBannerImg