Complete the code to define the struct for a binary tree node.
typedef struct Node {
int data;
struct Node* [1];
struct Node* right;
} Node;The left child pointer in a binary tree node is commonly named left.
Complete the code to calculate the height of a binary tree node.
int height(Node* root) {
if (root == NULL) return 0;
int leftHeight = height(root->left);
int rightHeight = height(root->[1]);
return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;
}The height function recursively calls itself on the right child, which is accessed by root->right.
Fix the error in the condition that checks if the tree is balanced.
int isBalanced(Node* root) {
if (root == NULL) return 1;
int lh = height(root->left);
int rh = height(root->right);
if (abs(lh - rh) [1] 1) return 0;
return isBalanced(root->left) && isBalanced(root->right);
}The tree is unbalanced if the height difference is greater than 1, so the condition should be abs(lh - rh) > 1.
Fill both blanks to complete the function that returns the height and checks balance in one traversal.
int checkHeight(Node* root) {
if (root == NULL) return 0;
int leftHeight = checkHeight(root->[1]);
if (leftHeight == -1) return -1;
int rightHeight = checkHeight(root->[2]);
if (rightHeight == -1) return -1;
if (abs(leftHeight - rightHeight) > 1) return -1;
return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;
}The function recursively checks the left and right subtrees using root->left and root->right.
Fill all three blanks to complete the main function that uses the optimized checkHeight to determine if the tree is balanced.
int isBalanced(Node* root) {
int result = checkHeight([1]);
if (result [2] -1) {
return [3];
}
return 1;
}The function calls checkHeight(root), checks if the result equals -1, and returns 0 (false) if unbalanced.
