Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the data field for the node value.
DSA Java
public class TreeNode { int [1]; TreeNode left; TreeNode right; public TreeNode(int val) { this.val = val; left = null; right = null; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'value' or 'data' instead of 'val' causes mismatch with constructor.
✗ Incorrect
The node value is stored in the field named 'val' as per the constructor and usage.
2fill in blank
mediumComplete the code to assign the left child node.
DSA Java
public void setLeftChild(TreeNode [1]) { this.left = [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name than declared causes errors.
✗ Incorrect
The parameter name is 'child' and it is assigned to 'left'.
3fill in blank
hardFix the error in the constructor parameter name to match the field assignment.
DSA Java
public TreeNode(int [1]) {
this.val = val;
left = null;
right = null;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name causes 'val' to be undefined.
✗ Incorrect
The parameter must be named 'val' to match the assignment 'this.val = val;'.
4fill in blank
hardFill both blanks to complete the method that returns true if the node is a leaf (no children).
DSA Java
public boolean isLeaf() {
return this.left [1] null && this.right [2] null;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' instead of '==' causes wrong leaf detection.
Using logical OR '||' instead of AND '&&' causes incorrect results.
✗ Incorrect
A node is a leaf if both left and right are equal to null.
5fill in blank
hardFill all three blanks to complete the method that returns the number of children (0, 1, or 2).
DSA Java
public int childrenCount() {
int count = 0;
if (this.left [1] null) count++;
if (this.right [2] null) count++;
return [3];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of '!=' in conditions causes wrong count.
Returning 'this.count' instead of local 'count' causes errors.
✗ Incorrect
Count increments if left or right child is not null, then returns count.
