Balanced Binary Tree or Not
Last Updated :
12 Feb, 2025
Given a binary tree, determine if it is height-balanced. A binary tree is considered height-balanced if the absolute difference in heights of the left and right subtrees is at most 1 for every node in the tree.
Examples:
Input:

Output: True
Explanation: The height difference between the left and right subtrees at all nodes is at most 1
. Hence, the tree is balanced.
Input:

Output: False
Explanation: The height difference between the left and right subtrees at node 2
is 2
, which exceeds 1
. Hence, the tree is not balanced.
[Naive Approach] Using Top Down Recursion - O(n^2) Time and O(h) Space
A simple approach is to compute the absolute difference between the heights of the left and right subtrees for each node of the tree using DFS traversal. If, for any node, this absolute difference becomes greater than one, then the entire tree is not height-balanced.
C++
// C++ program to check if a tree is height-balanced or not
// Using Top Down Recursion
#include <iostream>
using namespace std;
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: Height of empty tree is zero
if (node == NULL)
return 0;
// Height = 1 + max of left height and right heights
return 1 + max(height(node->left), height(node->right));
}
// Function to check if the binary tree with given root, is height-balanced
bool isBalanced(Node* root) {
// If tree is empty then return true
if (root == NULL)
return true;
// Get the height of left and right sub trees
int lHeight = height(root->left);
int rHeight = height(root->right);
// If absolute height difference is greater than 1
// Then return false
if (abs(lHeight - rHeight) > 1)
return false;
// Recursively check the left and right subtrees
return isBalanced(root->left) && isBalanced(root->right);
}
int main() {
// Representation of input BST:
// 1
// / \
// 2 3
// / \
// 4 5
// /
// 8
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);
cout << (isBalanced(root) ? "True" : "False");
return 0;
}
C
// C program to check if a tree is height-balanced or not
// Using Top Down Recursion
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
// Define the structure for a binary tree node
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to create a new 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;
}
// Function to calculate the height of a tree
int height(struct Node* node) {
// Base case: Height of empty tree is zero
if (node == NULL)
return 0;
// Height = 1 + max of left height and right heights
return 1 + fmax(height(node->left), height(node->right));
}
// Function to check if the binary tree with given root is height-balanced
bool isBalanced(struct Node* root) {
// If tree is empty then return true
if (root == NULL)
return true;
// Get the height of left and right subtrees
int lHeight = height(root->left);
int rHeight = height(root->right);
// If absolute height difference is greater than 1
// Then return false
if (abs(lHeight - rHeight) > 1)
return false;
// Recursively check the left and right subtrees
return isBalanced(root->left) && isBalanced(root->right);
}
int main() {
// Representation of input BST:
// 1
// / \
// 2 3
// / \
// 4 5
// /
// 8
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);
printf("%s\n", isBalanced(root) ? "True" : "False");
return 0;
}
Java
// Java program to check if a tree is height-balanced or not
// Using Top Down Recursion
class Node {
int data;
Node left, right;
Node(int d) {
data = d;
left = right = null;
}
}
class GfG {
// Function to calculate the height of a tree
static int height(Node node) {
// Base case: Height of empty tree is zero
if (node == null)
return 0;
// Height = 1 + max of left height and right heights
return 1 + Math.max(height(node.left), height(node.right));
}
// Function to check if the binary tree with given root is height-balanced
static boolean isBalanced(Node root) {
// If tree is empty then return true
if (root == null)
return true;
// Get the height of left and right subtrees
int lHeight = height(root.left);
int rHeight = height(root.right);
// If absolute height difference is greater than 1
// Then return false
if (Math.abs(lHeight - rHeight) > 1)
return false;
// Recursively check the left and right subtrees
return isBalanced(root.left) && isBalanced(root.right);
}
public static void main(String[] args) {
// Representation of input BST:
// 1
// / \
// 2 3
// / \
// 4 5
// /
// 8
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);
System.out.println(isBalanced(root) ? "True" : "False");
}
}
Python
# Python program to check if a tree is height-balanced or not
# Using Top Down Recursion
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to calculate the height of a tree
def height(node):
# Base case: Height of empty tree is zero
if node is None:
return 0
# Height = 1 + max of left height and right heights
return 1 + max(height(node.left), height(node.right))
# Function to check if the binary tree with given root is height-balanced
def isBalanced(root):
# If tree is empty then return true
if root is None:
return True
# Get the height of left and right subtrees
lHeight = height(root.left)
rHeight = height(root.right)
# If absolute height difference is greater than 1
# Then return false
if abs(lHeight - rHeight) > 1:
return False
# Recursively check the left and right subtrees
return isBalanced(root.left) and isBalanced(root.right)
if __name__ == "__main__":
# Representation of input BST:
# 1
# / \
# 2 3
# / \
# 4 5
# /
# 8
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)
print("True" if isBalanced(root) else "False")
C#
// C# program to check if a tree is height-balanced or not
// Using Top Down Recursion
using System;
class Node {
public int data;
public Node left, right;
public Node(int d) {
data = d;
left = right = null;
}
}
class GfG {
// Function to calculate the height of a tree
static int height(Node node) {
// Base case: Height of empty tree is zero
if (node == null)
return 0;
// Height = 1 + max of left height and right heights
return 1 + Math.Max(height(node.left), height(node.right));
}
// Function to check if the binary tree with given root is height-balanced
static bool isBalanced(Node root) {
// If tree is empty then return true
if (root == null)
return true;
// Get the height of left and right subtrees
int lHeight = height(root.left);
int rHeight = height(root.right);
// If absolute height difference is greater than 1
// Then return false
if (Math.Abs(lHeight - rHeight) > 1)
return false;
// Recursively check the left and right subtrees
return isBalanced(root.left) && isBalanced(root.right);
}
static void Main() {
// Representation of input BST:
// 1
// / \
// 2 3
// / \
// 4 5
// /
// 8
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);
Console.WriteLine(isBalanced(root) ? "True" : "False");
}
}
JavaScript
// JavaScript program to check if a tree is height-balanced or not
// Using Top Down Recursion
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
// Function to calculate the height of a tree
function height(node) {
// Base case: Height of empty tree is zero
if (node === null)
return 0;
// Height = 1 + max of left height and right heights
return 1 + Math.max(height(node.left), height(node.right));
}
// Function to check if the binary tree with given root is height-balanced
function isBalanced(root) {
// If tree is empty then return true
if (root === null)
return true;
// Get the height of left and right subtrees
let lHeight = height(root.left);
let rHeight = height(root.right);
// If absolute height difference is greater than 1
// Then return false
if (Math.abs(lHeight - rHeight) > 1)
return false;
// Recursively check the left and right subtrees
return isBalanced(root.left) && isBalanced(root.right);
}
// Driver Code
// Representation of input BST:
// 1
// / \
// 2 3
// / \
// 4 5
// /
// 8
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);
console.log(isBalanced(root) ? "True" : "False");
[Expected Approach]Using Bottom Up Recursion - O(n) Time and O(h) Space
The above approach can be optimised by calculating the height in the same function 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.
C++
// C++ program to check if a tree is height-balanced or not
// Using Bottom Up Recursion
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int d) {
int data = d;
left = right = NULL;
}
};
// Function that returns the height of the tree if the tree is balanced
// Otherwise it returns -1.
int isBalancedRec(Node* root) {
// Base case: Height of empty tree is zero
if (root == NULL)
return 0;
// Find Heights of left and right sub trees
int lHeight = isBalancedRec(root->left);
int rHeight = isBalancedRec(root->right);
// If either the subtrees are unbalanced or the absolute difference
// of their heights is greater than 1, return -1
if (lHeight == -1 || rHeight == -1 || abs(lHeight - rHeight) > 1)
return -1;
// Return the height of the tree
return max(lHeight, rHeight) + 1;
}
// Function to check if tree is height balanced
bool isBalanced(Node *root) {
return (isBalancedRec(root) > 0);
}
int main() {
// Representation of input BST:
// 1
// / \
// 2 3
// / \
// 4 5
// /
// 8
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);
cout << (isBalanced(root) ? "True" : "False");
return 0;
}
C
// C program to check if a tree is height-balanced or not
// Using Bottom Up Recursion
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
// Function to create a new node
Node* newNode(int d) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = d;
node->left = node->right = NULL;
return node;
}
// Function that returns the height of the tree if the tree is balanced
// Otherwise it returns -1
int isBalancedRec(Node* root) {
// Base case: Height of empty tree is zero
if (root == NULL)
return 0;
// Find Heights of left and right subtrees
int lHeight = isBalancedRec(root->left);
int rHeight = isBalancedRec(root->right);
// If either of the subtrees are unbalanced or the absolute difference
// of their heights is greater than 1, return -1
if (lHeight == -1 || rHeight == -1 || abs(lHeight - rHeight) > 1)
return -1;
// Return the height of the tree
return fmax(lHeight, rHeight) + 1;
}
// Function to check if the tree is height balanced
int isBalanced(Node* root) {
return (isBalancedRec(root) > 0);
}
int main() {
// Representation of input BST:
// 1
// / \
// 2 3
// / \
// 4 5
// /
// 8
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);
printf(isBalanced(root) ? "True\n" : "False\n");
return 0;
}
Java
// Java program to check if a tree is height-balanced or not
// Using Bottom Up Recursion
class Node {
int data;
Node left, right;
Node(int d) {
data = d;
left = right = null;
}
}
class GfG {
// Function that returns the height of the tree if the tree is balanced
// Otherwise it returns -1
static int isBalancedRec(Node root) {
// Base case: Height of empty tree is zero
if (root == null)
return 0;
// Find Heights of left and right subtrees
int lHeight = isBalancedRec(root.left);
int rHeight = isBalancedRec(root.right);
// If either of the subtrees are unbalanced or the absolute difference
// of their heights is greater than 1, return -1
if (lHeight == -1 || rHeight == -1 || Math.abs(lHeight - rHeight) > 1)
return -1;
// Return the height of the tree
return Math.max(lHeight, rHeight) + 1;
}
// Function to check if the tree is height balanced
static boolean isBalanced(Node root) {
return isBalancedRec(root) > 0;
}
public static void main(String[] args) {
// Representation of input BST:
// 1
// / \
// 2 3
// / \
// 4 5
// /
// 8
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);
System.out.println(isBalanced(root) ? "True" : "False");
}
}
Python
# Python program to check if a tree is height-balanced or not
# Using Bottom Up Recursion
class Node:
def __init__(self, d):
self.data = d
self.left = None
self.right = None
# Function that returns the height of the tree if the tree is balanced
# Otherwise it returns -1
def isBalancedRec(root):
# Base case: Height of empty tree is zero
if root is None:
return 0
# Find Heights of left and right subtrees
lHeight = isBalancedRec(root.left)
rHeight = isBalancedRec(root.right)
# If either of the subtrees are unbalanced or the absolute difference
# of their heights is greater than 1, return -1
if lHeight == -1 or rHeight == -1 or abs(lHeight - rHeight) > 1:
return -1
# Return the height of the tree
return max(lHeight, rHeight) + 1
# Function to check if the tree is height balanced
def isBalanced(root):
return isBalancedRec(root) > 0
if __name__ == "__main__":
# Representation of input BST:
# 1
# / \
# 2 3
# / \
# 4 5
# /
# 8
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)
print("True" if isBalanced(root) else "False")
C#
// C# program to check if a tree is height-balanced or not
// Using Bottom Up Recursion
using System;
class Node {
public int data;
public Node left, right;
public Node(int d) {
data = d;
left = right = null;
}
}
class GfG {
// Function that returns the height of the tree if the tree is balanced
// Otherwise it returns -1
static int isBalancedRec(Node root) {
// Base case: Height of empty tree is zero
if (root == null)
return 0;
// Find Heights of left and right subtrees
int lHeight = isBalancedRec(root.left);
int rHeight = isBalancedRec(root.right);
// If either of the subtrees are unbalanced or the absolute difference
// of their heights is greater than 1, return -1
if (lHeight == -1 || rHeight == -1 || Math.Abs(lHeight - rHeight) > 1)
return -1;
// Return the height of the tree
return Math.Max(lHeight, rHeight) + 1;
}
// Function to check if the tree is height balanced
static bool isBalanced(Node root) {
return isBalancedRec(root) > 0;
}
public static void Main(string[] args) {
// Representation of input BST:
// 1
// / \
// 2 3
// / \
// 4 5
// /
// 8
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);
Console.WriteLine(isBalanced(root) ? "True" : "False");
}
}
JavaScript
// JavaScript program to check if a tree is height-balanced or not
// Using Bottom Up Recursion
class Node {
constructor(d) {
this.data = d;
this.left = null;
this.right = null;
}
}
// Function that returns the height of the tree if the tree is balanced
// Otherwise it returns -1
function isBalancedRec(root) {
// Base case: Height of empty tree is zero
if (root === null)
return 0;
// Find Heights of left and right subtrees
let lHeight = isBalancedRec(root.left);
let rHeight = isBalancedRec(root.right);
// If either of the subtrees are unbalanced or the absolute difference
// of their heights is greater than 1, return -1
if (lHeight === -1 || rHeight === -1 || Math.abs(lHeight - rHeight) > 1)
return -1;
// Return the height of the tree
return Math.max(lHeight, rHeight) + 1;
}
// Function to check if the tree is height balanced
function isBalanced(root) {
return isBalancedRec(root) > 0;
}
// Driver Code
// Representation of input BST:
// 1
// / \
// 2 3
// / \
// 4 5
// /
// 8
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);
console.log(isBalanced(root) ? "True" : "False");
Similar Reads
Binary Search Tree A Binary Search Tree (BST) is a type of binary tree data structure in which each node contains a unique key and satisfies a specific ordering property:All nodes in the left subtree of a node contain values strictly less than the nodeâs value. All nodes in the right subtree of a node contain values s
4 min read
Introduction to Binary Search Tree Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Binary search tree follows all properties of binary tree and for every nodes, its left subtree contains values less than the node and the right subtree contains values greater than the
3 min read
Applications of BST Binary Search Tree (BST) is a data structure that is commonly used to implement efficient searching, insertion, and deletion operations along with maintaining sorted sequence of data. Please remember the following properties of BSTs before moving forward.The left subtree of a node contains only node
3 min read
Applications, Advantages and Disadvantages of Binary Search Tree A Binary Search Tree (BST) is a data structure used to storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the p
2 min read
Insertion in Binary Search Tree (BST) Given a BST, the task is to insert a new node in this BST.Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is fo
15 min read
Searching in Binary Search Tree (BST) Given a BST, the task is to search a node in this BST. For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInp
7 min read
Deletion in Binary Search Tree (BST) Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios:Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BSTDeleting a single child node is also simple in BST. Copy the child to the node and delete the node. Case 3. Delete a Node w
10 min read
Binary Search Tree (BST) Traversals â Inorder, Preorder, Post Order Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree. Input: A Binary Search TreeOutput: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 1
10 min read
Balance a Binary Search Tree Given a BST (Binary Search Tree) that may be unbalanced, the task is to convert it into a balanced BST that has the minimum possible height.Examples: Input: Output: Explanation: The above unbalanced BST is converted to balanced with the minimum possible height.Input: Output: Explanation: The above u
10 min read
Self-Balancing Binary Search Trees Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keep the height as small as possible when insertion and deletion operations are performed on the tree. The height is typically maintained in order of logN so that all operations take O(logN) time on average
4 min read