Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the struct for a binary tree node.
DSA C
struct TreeNode {
int val;
struct TreeNode *[1];
struct TreeNode *right;
};Attempts:
3 left
💡 Hint
Common Mistakes
Using 'root' or 'node' instead of 'left' for the left child pointer.
✗ Incorrect
The left child pointer in a binary tree node is usually named 'left'.
2fill in blank
mediumComplete the code to calculate the maximum of two integers.
DSA C
int max(int a, int b) { return (a [1] b) ? a : b; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' which returns the minimum instead of maximum.
✗ Incorrect
To find the maximum, return 'a' if a > b, else return b.
3fill in blank
hardFix the error in the recursive function to find the height of the tree.
DSA C
int height(struct TreeNode* root) {
if (root == NULL) {
return [1];
}
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning 1 or NULL instead of 0 for the base case.
✗ Incorrect
The height of an empty tree is 0, so return 0 when root is NULL.
4fill in blank
hardFill both blanks to update the diameter during recursion.
DSA C
int diameter = 0; int height(struct TreeNode* root) { if (root == NULL) return 0; int leftHeight = height(root->[1]); int rightHeight = height(root->[2]); int maxDiameter = leftHeight + rightHeight; if (maxDiameter > diameter) diameter = maxDiameter; return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'root' or 'child' instead of 'left' and 'right' pointers.
✗ Incorrect
To calculate diameter, we need heights of left and right subtrees, so use 'left' and 'right'.
5fill in blank
hardFill all three blanks to complete the diameterOfBinaryTree function.
DSA C
int diameterOfBinaryTree(struct TreeNode* root) {
diameter = 0;
[1](root);
return [2];
}
// Helper function
int [3](struct TreeNode* root);Attempts:
3 left
💡 Hint
Common Mistakes
Calling diameterOfBinaryTree recursively causing infinite loop.
Returning height instead of diameter.
✗ Incorrect
Call height(root) to update diameter, then return diameter. The helper function is height.
