0
0
DSA C++programming~10 mins

Check if Binary Tree is Balanced in DSA C++ - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to return the height of the tree.

DSA C++
int height(TreeNode* root) {
    if (root == nullptr) return [1];
    return 1 + std::max(height(root->left), height(root->right));
}
Drag options to blanks, or click blank then click option'
A-1
B1
C0
DNULL
Attempts:
3 left
💡 Hint
Common Mistakes
Returning 1 instead of 0 for an empty tree.
Returning NULL which is not an integer.
2fill in blank
medium

Complete the code to check if the height difference between left and right subtrees is more than 1.

DSA C++
bool isBalanced(TreeNode* root) {
    if (root == nullptr) return true;
    int lh = height(root->left);
    int rh = height(root->right);
    if (std::abs(lh - rh) > [1]) return false;
    return isBalanced(root->left) && isBalanced(root->right);
}
Drag options to blanks, or click blank then click option'
A0
B-1
C2
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 which means no difference allowed.
Using 2 which is too large.
3fill in blank
hard

Fix the error in the height function to avoid redundant calls.

DSA C++
int height(TreeNode* root) {
    if (root == nullptr) return 0;
    int lh = height(root->left);
    int rh = height(root->right);
    if (lh == -1 || rh == -1 || std::abs(lh - rh) > 1) return [1];
    return 1 + std::max(lh, rh);
}
Drag options to blanks, or click blank then click option'
A0
B-1
C1
DINT_MIN
Attempts:
3 left
💡 Hint
Common Mistakes
Returning 0 which is a valid height.
Returning INT_MIN which is not standard here.
4fill in blank
hard

Fill both blanks to complete the optimized balanced check function.

DSA C++
int checkHeight(TreeNode* root) {
    if (root == nullptr) return [1];
    int lh = checkHeight(root->left);
    if (lh == [2]) return -1;
    int rh = checkHeight(root->right);
    if (rh == -1) return -1;
    if (std::abs(lh - rh) > 1) return -1;
    return 1 + std::max(lh, rh);
}
Drag options to blanks, or click blank then click option'
A0
B-1
C1
DNULL
Attempts:
3 left
💡 Hint
Common Mistakes
Returning NULL which is not an int.
Not checking for -1 to propagate imbalance.
5fill in blank
hard

Fill all three blanks to complete the final balanced tree check function.

DSA C++
bool isBalanced(TreeNode* root) {
    return checkHeight(root) != [1];
}

int checkHeight(TreeNode* root) {
    if (root == nullptr) return [2];
    int lh = checkHeight(root->left);
    if (lh == [3]) return -1;
    int rh = checkHeight(root->right);
    if (rh == -1) return -1;
    if (std::abs(lh - rh) > 1) return -1;
    return 1 + std::max(lh, rh);
}
Drag options to blanks, or click blank then click option'
A-1
B0
C1
DNULL
Attempts:
3 left
💡 Hint
Common Mistakes
Using NULL which is not an int.
Not comparing checkHeight result to -1.