Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the maximum of two integers.
DSA Java
int max(int a, int b) { return (a [1] b) ? a : b; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' will return the minimum instead of maximum.
Using '==' or '!=' will not compare sizes correctly.
✗ Incorrect
The max function returns a if a is greater than b, otherwise b.
2fill in blank
mediumComplete the code to calculate the height of a binary tree node.
DSA Java
int height(TreeNode node) {
if (node == null) return 0;
return 1 + Math.[1](height(node.left), height(node.right));
}Attempts:
3 left
💡 Hint
Common Mistakes
Using Math.min will give the shorter subtree height, which is incorrect.
Using Math.abs or Math.sum are not valid methods for this purpose.
✗ Incorrect
The height of a node is 1 plus the maximum height of its left or right subtree.
3fill in blank
hardFix the error in updating the diameter during recursion.
DSA Java
int diameter = 0; int height(TreeNode node) { if (node == null) return 0; int leftHeight = height(node.left); int rightHeight = height(node.right); diameter = Math.[1](diameter, leftHeight + rightHeight); return 1 + Math.max(leftHeight, rightHeight); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using Math.min will incorrectly reduce the diameter.
Using Math.abs or Math.sum are not valid for this update.
✗ Incorrect
We update diameter to the maximum of current diameter and sum of left and right heights.
4fill in blank
hardFill both blanks to complete the diameterOfBinaryTree method.
DSA Java
public int diameterOfBinaryTree(TreeNode root) {
diameter = 0;
[1](root);
return [2];
}Attempts:
3 left
💡 Hint
Common Mistakes
Calling maxDepth instead of height will cause errors if maxDepth is undefined.
Returning root instead of diameter will return the wrong value.
✗ Incorrect
We call height to compute heights and update diameter, then return diameter.
5fill in blank
hardFill all three blanks to complete the height method with diameter update.
DSA Java
int height(TreeNode node) {
if (node == null) return 0;
int leftHeight = [1](node.left);
int rightHeight = [2](node.right);
diameter = Math.[3](diameter, leftHeight + rightHeight);
return 1 + Math.max(leftHeight, rightHeight);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using min instead of max for diameter update.
Calling max or sum instead of height for subtree heights.
✗ Incorrect
We recursively call height on left and right children, then update diameter with max.
