Complete the code to return the height of the binary tree.
int height(struct Node* root) {
if (root == NULL) {
return [1];
}
// rest of the code
}The height of an empty tree is -1, so we return -1 when the root is NULL.
Complete the code to calculate the height by comparing left and right subtree heights.
int height(struct Node* root) {
if (root == NULL) {
return 0;
}
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return (leftHeight [1] rightHeight ? leftHeight : rightHeight) + 1;
}We need to find the maximum height between left and right subtrees, so we use the greater than operator to compare.
Fix the error in the code to correctly return the maximum height.
int max(int a, int b) { if (a [1] b) return a; else return b; } int height(struct Node* root) { if (root == NULL) { return 0; } return max(height(root->left), height(root->right)) + 1; }
The max function should return 'a' if 'a' is greater than 'b'. So the correct operator is '>'.
Fill both blanks to complete the recursive height calculation using the max function.
int height(struct Node* root) {
if (root == NULL) {
return [1];
}
int leftHeight = height(root->[2]);
int rightHeight = height(root->right);
return max(leftHeight, rightHeight) + 1;
}Return 0 for empty tree. To get left subtree height, use root->left.
Fill all three blanks to complete the height function using max and recursive calls.
int height(struct Node* root) {
if (root == [1]) {
return 0;
}
int leftHeight = height(root->[2]);
int rightHeight = height(root->[3]);
return max(leftHeight, rightHeight) + 1;
}Check if root is NULL. Then recursively get left and right subtree heights using root->left and root->right.
