int isBalancedHelper(TreeNode *root) {
    if (!root) {
        return 0;
    }
    int leftHeight = isBalancedHelper(root -> left);
    int rightHeight = isBalancedHelper(root ->right);
    
    if (abs(leftHeight - rightHeight) > 1 || leftHeight == -1 || rightHeight == -1) {
        return -1;
    }
    return max(leftHeight, rightHeight) + 1;
}
Example #2
0
bool isBalancedHelper(TreeNode *root,int &height) {
    if (root == NULL) {
        height = 0;
        return true;
    }
    int leftHeight,rightHeight;
    if (!isBalancedHelper(root->left,leftHeight)) return false;
    if (!isBalancedHelper(root->right,rightHeight)) return false;
    if (leftHeight - rightHeight > 1 || leftHeight - rightHeight < -1) return false;
    height = max(leftHeight,rightHeight) + 1;
    return true;
}
bool isBalanced(TreeNode* root) {
	if (isBalancedHelper(root) == -1) {
        return false;
    } else {
        return true;
    }
}
Example #4
0
bool isBalanced(TreeNode *root) {
    int height = 0;
    return isBalancedHelper(root,height);
}
bool isBalanced(TreeNode* root) {
    return isBalancedHelper(root) != -1;
}