Complete the code to return the height of the tree.
int height(TreeNode* root) {
if (root == nullptr) return [1];
return 1 + std::max(height(root->left), height(root->right));
}The height of an empty tree is 0.
Complete the code to check if the height difference between left and right subtrees is more than 1.
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);
}A binary tree is balanced if the height difference between left and right subtree is at most 1.
Fix the error in the height function to avoid redundant calls.
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);
}Return -1 to indicate the tree is not balanced at this node.
Fill both blanks to complete the optimized balanced check function.
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);
}Return 0 for empty tree height and -1 to indicate imbalance.
Fill all three blanks to complete the final balanced tree check function.
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);
}The function returns false if checkHeight returns -1 indicating imbalance.
Empty tree height is 0.
-1 signals imbalance.
