4.1 Implement a function to check if a binary tree is balanced. For the purpose of this question, a balanced tree is defined to be a tree such that the height of the two subtrees of any node never differ by more than one.
struct TreeNode {
int data;
TreeNode *left, *right;
TreeNode(int v) : data(v), left(NULL), right(NULL) {}
};
int checkHeight(TreeNode *node) {
if (node == NULL) {
return 0;
}
int leftHeight = checkHeight(node->left);
if (leftHeight == -1) {
return -1;
}
int rightHeight = checkHeight(node->right);
if (rightHeight == -1) {
return -1;
}
if (abs(leftHeight - rightHeight) > 1) {
return -1;
} else {
return max(leftHeight, rightHeight) + 1;
}
}
bool isBalanced(TreeNode *node) {
return checkHeight(node) != -1;
}