Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define the structure for a binary tree node.
DSA C
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *[1];
} TreeNode;Attempts:
3 left
💡 Hint
Common Mistakes
Using 'parent' or 'next' instead of 'right' for the right child pointer.
✗ Incorrect
The right child pointer in a binary tree node is named 'right'.
2fill in blank
mediumComplete the code to update the maximum path sum if the current path sum is greater.
DSA C
if (currentSum > [1]) { maxSum = currentSum; }
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing currentSum with maxSum + 1 or other incorrect values.
✗ Incorrect
We compare currentSum with maxSum to update maxSum if currentSum is greater.
3fill in blank
hardFix the error in the recursive function to return the maximum gain from the current node.
DSA C
int maxGain(TreeNode* node, int* maxSum) {
if (node == NULL) return 0;
int leftGain = max(0, maxGain(node->left, maxSum));
int rightGain = max(0, maxGain(node->[1], maxSum));
int priceNewpath = node->val + leftGain + rightGain;
if (priceNewpath > *maxSum) *maxSum = priceNewpath;
return node->val + (leftGain > rightGain ? leftGain : rightGain);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'parent' or 'next' instead of 'right' for the right child pointer.
✗ Incorrect
The right child pointer is 'right', so we recurse on node->right.
4fill in blank
hardFill both blanks to complete the max function and the recursive call for left child.
DSA C
int max(int a, int b) { return (a [1] b) ? a : b; } int maxGain(TreeNode* node, int* maxSum) { if (node == NULL) return 0; int leftGain = max(0, maxGain(node->[2], maxSum));
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' in max function or wrong child pointer names.
✗ Incorrect
The max function uses '>' to return the larger value, and the left child pointer is 'left'.
5fill in blank
hardFill all three blanks to complete the main function that initializes maxSum and calls maxGain.
DSA C
int maxPathSum(TreeNode* root) {
int maxSum = [1];
maxGain(root, &[2]);
return [3];
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing maxSum to 0 or not passing it by reference.
✗ Incorrect
maxSum is initialized to the smallest integer, passed by reference, and returned after computation.
