Given the root of a binary tree, determine if it is height-balancedor not.
Note: 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: root = [10, 20, 30, 40, 60]
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: root = [1, 2, 3, 4, N, N, N, 5]
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] By Calculating Height For Each Node - 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.
Working of Approach:
Start from the root and recursively compute the height of its left and right subtrees.
For every node, compare the heights of its left and right subtrees. If the difference is greater than 1, the tree is not height-balanced.
If the current node is balanced, recursively perform the same check for its left and right children.
The tree is considered height-balanced only if every node satisfies the height difference condition.
Finally, return true if all nodes are balanced; otherwise, return false.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intd){data=d;left=right=nullptr;}};// Function to calculate the height of a treeintheight(Node*node){if(node==NULL)return0;// Height = 1 + max of left height and right heightsreturn1+max(height(node->left),height(node->right));}// Function to check if the binary tree with given root, is height-balancedboolisBalanced(Node*root){if(root==NULL)returntrue;// Get the height of left and right sub treesintlHeight=height(root->left);intrHeight=height(root->right);if(abs(lHeight-rHeight)>1)returnfalse;// Recursively check the left and right subtreesreturnisBalanced(root->left)&&isBalanced(root->right);}intmain(){// Representation of input BST:// 10// / \ // 20 30// / \ // 40 60Node*root=newNode(10);root->left=newNode(20);root->right=newNode(30);root->left->left=newNode(40);root->left->right=newNode(60);cout<<(isBalanced(root)?"true":"false");return0;}
Java
classNode{intdata;Nodeleft;Noderight;Node(intd){intdata=d;this.left=null;this.right=null;}}classGFG{// Function to calculate the height of a treestaticintheight(Nodenode){if(node==null)return0;// Height = 1 + max of left height and right heightsreturn1+Math.max(height(node.left),height(node.right));}// Function to check if the binary tree with given root// is height-balancedstaticbooleanisBalanced(Noderoot){if(root==null)returntrue;// Get the height of left and right sub treesintlHeight=height(root.left);intrHeight=height(root.right);if(Math.abs(lHeight-rHeight)>1)returnfalse;// Recursively check the left and right subtreesreturnisBalanced(root.left)&&isBalanced(root.right);}publicstaticvoidmain(String[]args){// Representation of input BST:// 10// / \// 20 30// / \// 40 60Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);System.out.println(isBalanced(root)?"true":"false");}}
Python
classNode:def__init__(self,d):self.data=dself.left=Noneself.right=None# Function to calculate the height of a treedefheight(node):ifnodeisNone:return0# Height = 1 + max of left height and right heightsreturn1+max(height(node.left),height(node.right))# Function to check if the binary tree with given root# is height-balanceddefisBalanced(root):ifrootisNone:returnTrue# Get the height of left and right sub treeslHeight=height(root.left)rHeight=height(root.right)ifabs(lHeight-rHeight)>1:returnFalse# Recursively check the left and right subtreesreturnisBalanced(root.left)andisBalanced(root.right)if__name__=="__main__":# Representation of input BST:# 10# / \# 20 30# / \# 40 60root=Node(10)root.left=Node(20)root.right=Node(30)root.left.left=Node(40)root.left.right=Node(60)print("true"ifisBalanced(root)else"false")
C#
usingSystem;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intd){this.data=d;this.left=null;this.right=null;}}classGFG{// Function to calculate the height of a treestaticintheight(Nodenode){if(node==null)return0;// Height = 1 + max of left height and right heightsreturn1+Math.Max(height(node.left),height(node.right));}// Function to check if the binary tree // with given root, is height-balancedstaticboolisBalanced(Noderoot){if(root==null)returntrue;// Get the height of left and right sub treesintlHeight=height(root.left);intrHeight=height(root.right);if(Math.Abs(lHeight-rHeight)>1)returnfalse;// Recursively check the left and right subtreesreturnisBalanced(root.left)&&isBalanced(root.right);}staticvoidMain(){// Representation of input BST:// 10// / \// 20 30// / \// 40 60Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);Console.WriteLine(isBalanced(root)?"true":"false");}}
JavaScript
// Node StructureclassNode{constructor(d){this.data=d;this.left=null;this.right=null;}}// Function to calculate the height of a treefunctionheight(node){if(node===null)return0;// Height = 1 + max of left height and right heightsreturn1+Math.max(height(node.left),height(node.right));}// Function to check if the binary tree with given root, is height-balancedfunctionisBalanced(root){if(root===null)returntrue;// Get the height of left and right sub treesconstlHeight=height(root.left);constrHeight=height(root.right);if(Math.abs(lHeight-rHeight)>1)returnfalse;// Recursively check the left and right subtreesreturnisBalanced(root.left)&&isBalanced(root.right);}// Driver Code// Representation of input BST:// 10// / \// 20 30// / \// 40 60constroot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);console.log(isBalanced(root)?"true":"false");
Output
true
[Expected Approach] Using Single Traversal - O(n) Time and O(h) Space
We can optimize by checking balance and calculating height in the same recursion. For each node, check its left and right subtrees. If both are balanced, return the subtree’s height; otherwise, return -1 to show it’s not balanced. This avoids extra height calculations.
Working of Approach:
Traverse the tree in postorder so the heights of the left and right subtrees are calculated before processing the current node.
Each recursive call returns the height of the subtree if it is balanced; otherwise, it returns -1 to indicate an unbalanced subtree.
At every node, compare the heights of the left and right subtrees. If their difference is greater than 1, immediately return -1.
If either subtree is already unbalanced, propagate -1 upward without performing further unnecessary calculations.
If the traversal completes without returning -1, the tree is height-balanced, and the function returns true.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intd){data=d;left=right=nullptr;}};// Function that returns the height of the tree if the tree is balanced// Otherwise it returns -1.intisBalancedRec(Node*root){if(root==nullptr)return0;// Find Heights of left and right sub treesintlHeight=isBalancedRec(root->left);intrHeight=isBalancedRec(root->right);// If either the subtrees are unbalanced or the absolute difference// of their heights is greater than 1, return -1if(lHeight==-1||rHeight==-1||abs(lHeight-rHeight)>1)return-1;returnmax(lHeight,rHeight)+1;}// Function to check if tree is height balancedboolisBalanced(Node*root){return(isBalancedRec(root)>=0);}intmain(){// Representation of input BST:// 10// / \ // 20 30// / \ // 40 60Node*root=newNode(10);root->left=newNode(20);root->right=newNode(30);root->left->left=newNode(40);root->left->right=newNode(60);cout<<(isBalanced(root)?"true":"false");return0;}
Java
classNode{intdata;Nodeleft;Noderight;Node(intd){this.data=d;left=right=null;}}classGFG{// Function that returns the height of the tree if the tree is balanced// Otherwise it returns -1.staticintisBalancedRec(Noderoot){if(root==null)return0;// Find Heights of left and right sub treesintlHeight=isBalancedRec(root.left);intrHeight=isBalancedRec(root.right);// If either the subtrees are unbalanced or the absolute difference // of their heights is greater than 1, return -1if(lHeight==-1||rHeight==-1||Math.abs(lHeight-rHeight)>1)return-1;returnMath.max(lHeight,rHeight)+1;}// Function to check if tree is height balancedstaticbooleanisBalanced(Noderoot){returnisBalancedRec(root)>0;}publicstaticvoidmain(String[]args){// Representation of input BST:// 10// / \// 20 30// / \// 40 60Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);System.out.println(isBalanced(root)?"true":"false");}}
Python
classNode:def__init__(self,d):self.data=dself.left=Noneself.right=None# Function that returns the height of the tree if the tree is balanced# Otherwise it returns -1defisBalancedRec(root):ifrootisNone:return0# Find Heights of left and right sub treeslHeight=isBalancedRec(root.left)rHeight=isBalancedRec(root.right)# If either the subtrees are unbalanced or the absolute difference # of their heights is greater than 1, return -1iflHeight==-1orrHeight==-1orabs(lHeight-rHeight)>1:return-1returnmax(lHeight,rHeight)+1# Function to check if tree is height balanceddefisBalanced(root):returnisBalancedRec(root)>0if__name__=="__main__":# Representation of input BST:# 10# / \# 20 30# / \# 40 60root=Node(10)root.left=Node(20)root.right=Node(30)root.left.left=Node(40)root.left.right=Node(60)print("true"ifisBalanced(root)else"false")
C#
usingSystem;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intd){this.data=d;left=null;right=null;}}classGFG{// Function that returns the height of the tree if the tree is balanced// Otherwise it returns -1staticintisBalancedRec(Noderoot){if(root==null)return0;// Find Heights of left and right sub treesintlHeight=isBalancedRec(root.left);intrHeight=isBalancedRec(root.right);// If either the subtrees are unbalanced or the absolute difference // of their heights is greater than 1, return -1if(lHeight==-1||rHeight==-1||Math.Abs(lHeight-rHeight)>1)return-1;returnMath.Max(lHeight,rHeight)+1;}// Function to check if tree is height balancedstaticboolisBalanced(Noderoot){returnisBalancedRec(root)>0;}staticvoidMain(){// Representation of input BST:// 10// / \// 20 30// / \// 40 60Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);Console.WriteLine(isBalanced(root)?"true":"false");}}
JavaScript
classNode{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 -1functionisBalancedRec(root){if(root===null)return0;// Find Heights of left and right sub treesconstlHeight=isBalancedRec(root.left);constrHeight=isBalancedRec(root.right);// If either the subtrees are unbalanced or the absolute// difference of their heights is greater than 1, return// -1if(lHeight===-1||rHeight===-1||Math.abs(lHeight-rHeight)>1)return-1;returnMath.max(lHeight,rHeight)+1;}// Function to check if tree is height balancedfunctionisBalanced(root){returnisBalancedRec(root)>0;}// Driver Code// Representation of input BST:// 10// / \// 20 30// / \// 40 60constroot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);console.log(isBalanced(root)?"true":"false");