Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define the TreeNode class with integer value and left/right children.
DSA C#
public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int [1]) { this.val = val; left = null; right = null; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name but not assigning it properly.
Forgetting to assign the parameter to the field.
✗ Incorrect
The constructor parameter should be named 'val' to assign it to the class field 'val'.
2fill in blank
mediumComplete the code to calculate the maximum path sum starting from the current node and going down one side.
DSA C#
private int MaxGain(TreeNode node) {
if (node == null) return 0;
int leftGain = Math.Max(MaxGain(node.left), [1]);
int rightGain = Math.Max(MaxGain(node.right), 0);
return node.val + Math.Max(leftGain, rightGain);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using node.val instead of 0, which can cause incorrect sums.
Using negative values that reduce the path sum.
✗ Incorrect
We use 0 as the minimum gain to ignore negative paths.
3fill in blank
hardFix the error in updating the global maximum path sum inside the MaxGain function.
DSA C#
maxSum = Math.Max(maxSum, node.val + leftGain + [1]);Attempts:
3 left
💡 Hint
Common Mistakes
Adding node.val twice.
Using only one side gain instead of both.
✗ Incorrect
The maximum path sum through the current node includes both left and right gains.
4fill in blank
hardFill both blanks to complete the MaxPathSum function that initializes and calls MaxGain.
DSA C#
public int MaxPathSum(TreeNode root) {
maxSum = [1];
MaxGain([2]);
return maxSum;
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing maxSum to 0 which may ignore negative sums.
Calling MaxGain with null instead of root.
✗ Incorrect
Initialize maxSum to smallest integer and start recursion from root.
5fill in blank
hardFill all three blanks to complete the MaxGain function with global maxSum update and return statement.
DSA C#
private int MaxGain(TreeNode node) {
if (node == null) return 0;
int leftGain = Math.Max(MaxGain(node.left), [1]);
int rightGain = Math.Max(MaxGain(node.right), [2]);
maxSum = Math.Max(maxSum, node.val + leftGain + [3]);
return node.val + Math.Max(leftGain, rightGain);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using node.val instead of 0 for gain comparison.
Not adding both left and right gains to maxSum.
✗ Incorrect
Use 0 to ignore negative gains, add left and right gains to maxSum, return node.val plus max gain.
