Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define the TreeNode structure with integer value and pointers to left and right children.
DSA C++
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right([1]) {}
}; Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 or NULL instead of nullptr for pointer initialization.
Forgetting to initialize right pointer.
✗ Incorrect
The constructor initializes left to nullptr and right to nullptr to indicate no child nodes initially.
2fill in blank
mediumComplete the code to update the maximum path sum using the current node's value and left/right path sums.
DSA C++
maxSum = std::max(maxSum, node->val + left + [1]);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Adding only one child's path sum.
Using max instead of sum of left and right.
✗ Incorrect
The maximum path sum at the current node includes the node's value plus left and right path sums.
3fill in blank
hardFix the error in the return statement to correctly return the maximum path sum for one side plus current node's value.
DSA C++
return node->val + std::max([1], 0);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning sum of left and right which is invalid for path continuation.
Not handling negative path sums.
✗ Incorrect
We return the node's value plus the maximum of left or right path sums, ignoring negative sums by comparing with 0.
4fill in blank
hardFill both blanks to complete the recursive function that calculates max path sums from left and right children.
DSA C++
int left = std::max(0, [1](node->left)); int right = std::max(0, [2](node->right));
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the main function name instead of helper for recursion.
Calling undefined functions.
✗ Incorrect
The helper function is called recursively on left and right children to get their max path sums.
5fill in blank
hardFill all three blanks to complete the main function that initializes maxSum and calls the helper.
DSA C++
int maxPathSum(TreeNode* root) {
int maxSum = [1];
maxPathSumHelper(root, maxSum);
return [2];
}
int maxPathSumHelper(TreeNode* node, int& maxSum) {
if (!node) return 0;
int left = std::max(0, maxPathSumHelper(node->left, maxSum));
int right = std::max(0, maxPathSumHelper(node->right, maxSum));
maxSum = std::max(maxSum, node->val + left + right);
return node->val + std::max(left, right);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing maxSum to 0 which fails for all negative nodes.
Returning 0 or uninitialized variable instead of maxSum.
✗ Incorrect
maxSum is initialized to INT_MIN to handle negative values, helper updates maxSum, and main returns maxSum.