Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

Balanced Binary Tree 🌟🌟

Given a binary tree, determine if it is height-balanced. A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

Brute force

Code

class Solution {
private:
    int height(TreeNode* root)
    {
        if (root == NULL) return 0;
        return 1 + max(height(root->left), height(root->right));
    }
public:

        bool isBalanced(TreeNode* root)
        {
            if (root == NULL) return true;
            int leftHeight = height(root->left);
            int rightHeight = height(root->right);

            if (abs(leftHeight - rightHeight) > 1) return false;

            return isBalanced(root->left) && isBalanced(root->right);
        }
    };

Optimized

Code

int heightOfBt(BinaryTreeNode<int>* root)
{
    if (!root) return 0;

    int lh = heightOfBt(root->left);
    if (lh == -1) return -1;

    int rh = heightOfBt(root->right);
    if (rh == -1) return -1;

    if (abs(lh - rh) > 1) return -1;

    return 1 + max(lh, rh);
}

bool isBalancedBT(BinaryTreeNode<int>* root)
{
    if (!root) return true;
    return heightOfBt(root) != -1;
}