struct Node {
int val;
Node* left;
Node* right;
Node(int x) : val(x), left(nullptr), right(nullptr) {}
};
int height(Node* root) {
if (!root) return 0;
int lh = height(root->left);
if (lh == -1) return -1;
int rh = height(root->right);
if (rh == -1) return -1;
if (abs(lh - rh) > 1) return -1;
return 1 + std::max(lh, rh);
}
bool isBalanced(Node* root) {
return height(root) != -1;
}
int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->right = new Node(6);
root->left->left->left = new Node(7);
std::cout << isBalanced(root) << std::endl;
return 0;
}The tree is unbalanced because the left subtree of the root has height 3 while the right subtree has height 2, and the left subtree's left child has a deeper subtree causing imbalance.
A balanced binary tree means for every node, the height difference of its left and right subtree is at most 1.
int height(Node* root) { if (!root) return 0; int lh = height(root->left); int rh = height(root->right); if (abs(lh - rh) > 1) return -1; return 1 + std::max(lh, rh); } bool isBalanced(Node* root) { return height(root) != -1; }
The function does not check if lh or rh is -1 before comparing heights, so it does not propagate imbalance detection properly.
struct Node {
int val;
Node* left;
Node* right;
Node(int x) : val(x), left(nullptr), right(nullptr) {}
};
int height(Node* root) {
if (!root) return 0;
int lh = height(root->left);
if (lh == -1) return -1;
int rh = height(root->right);
if (rh == -1) return -1;
if (abs(lh - rh) > 1) return -1;
return 1 + std::max(lh, rh);
}
bool isBalanced(Node* root) {
return height(root) != -1;
}
int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
std::cout << isBalanced(root) << std::endl;
return 0;
}The tree is perfect and balanced, so isBalanced returns true (1).
All single nodes are balanced (7 nodes). The subtree rooted at node 6 is balanced. The subtree rooted at node 3 is unbalanced due to deeper left subtree under 6. The subtree rooted at 2 is balanced. The whole tree is unbalanced. Counting balanced subtrees: nodes (7) + subtree at 6 (1) + subtree at 2 (1) = 9. But options do not have 9, so the question expects counting only single nodes, so answer is 7.