304 North Cardinal St.
Dorchester Center, MA 02124

# Balanced Binary Tree LeetCode Solution

## Problem – Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

Example 1:

``````Input: root = [3,9,20,null,null,15,7]
Output: true``````

Example 2:

``````Input: root = [1,2,2,3,3,null,null,4,4]
Output: false``````

Example 3:

``````Input: root = []
Output: true``````

Constraints:

• The number of nodes in the tree is in the range `[0, 5000]`.
• `-104 <= Node.val <= 104`

### Balanced Binary Tree LeetCode Solution in Python

``````class Solution(object):
def isBalanced(self, root):

def check(root):
if root is None:
return 0
left  = check(root.left)
right = check(root.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return 1 + max(left, right)

return check(root) != -1
``````

### Balanced Binary Tree LeetCode Solution in Java

``````public boolean isBalanced(TreeNode root) {
if(root==null){
return true;
}
return height(root)!=-1;

}
public int height(TreeNode node){
if(node==null){
return 0;
}
int lH=height(node.left);
if(lH==-1){
return -1;
}
int rH=height(node.right);
if(rH==-1){
return -1;
}
if(lH-rH<-1 || lH-rH>1){
return -1;
}
return Math.max(lH,rH)+1;
}
``````

### Balanced Binary Tree LeetCode Solution in C++

``````class Solution {
public:
bool ans;
int checkBalance(TreeNode* root){
if(!root)
return 0;
return 0;
int leftSubTree = checkBalance(root->left);
int rightSubTree = checkBalance(root->right);
if(abs(leftSubTree-rightSubTree) > 1){
ans = false;
}
return 1 + max(leftSubTree, rightSubTree);
}
bool isBalanced(TreeNode* root){
ans = true;
int temp = checkBalance(root);
return ans;
}
};
``````
##### Balanced Binary Tree LeetCode Solution Review:

In our experience, we suggest you solve this Balanced Binary Tree LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Balanced Binary Tree LeetCode Solution

Find on LeetCode

##### Conclusion:

I hope this Balanced Binary Tree LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions