3. What is the output of the following C code snippet that calculates the diameter of a binary tree?
struct Node {
int data;
struct Node* left;
struct Node* right;
};
int height(struct Node* root) {
if (!root) return 0;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}
int diameter(struct Node* root) {
if (!root) return 0;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
int leftDiameter = diameter(root->left);
int rightDiameter = diameter(root->right);
int maxDiameter = leftHeight + rightHeight + 1;
if (leftDiameter > maxDiameter) maxDiameter = leftDiameter;
if (rightDiameter > maxDiameter) maxDiameter = rightDiameter;
return maxDiameter;
}
int main() {
struct Node n1 = {1, NULL, NULL};
struct Node n2 = {2, NULL, NULL};
struct Node n3 = {3, &n1, &n2};
printf("%d", diameter(&n3));
return 0;
}