In this Leetcode Balanced Binary Tree problem solution we have 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.

Leetcode Balanced Binary Tree problem solution


Problem solution in Python.

class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        d = {}
        def ifbalanced(node):
            if not node:
                d[node] = 0
                return True
            elif not ifbalanced(node.left) or not ifbalanced(node.right):
                return False
            else:
                d[node] = max(d[node.left],d[node.right])+1
                return True if abs(d[node.left]-d[node.right]) <2 else False

        
        return ifbalanced(root)



Problem solution in Java.

class Solution {
    int max = 0;
    public boolean isBalanced(TreeNode root) {
        depth(root);
        return max <= 1; 
    }
    public int depth(TreeNode root) {
        if(root==null) return 0;
        int left = depth(root.left);
        int right = depth(root.right);
        max = Math.max(Math.abs(left-right), max);
        return 1 + Math.max(left, right);
    }
}


Problem solution in C++.

class Solution {
public:
    int height(TreeNode* root){
        if(root==NULL)
            return 0;
        return max(height(root->left),height(root->right)) + 1;
    }
    bool isBalanced(TreeNode* root) {
        if(root==NULL)
            return true;
        return abs(height(root->left) - height(root->right))<=1 && isBalanced(root->right) && isBalanced(root->left);
    }
};


Problem solution in C.

bool isBalanced(struct TreeNode* root) {
    bool ans = true;
    isBalancedHelper(root, &ans);
    return ans;
}

int isBalancedHelper(struct TreeNode * root, bool *answer) {
    if(!root) return 0;
    
    int left = isBalancedHelper(root -> left, answer);
    int right = isBalancedHelper(root -> right, answer);
    
    if(abs(left - right) > 1) {
        *answer = false;
    }
    
    return left > right ? left + 1 : right + 1;
}