Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the maximum path sum starting from the current node.
DSA C++
int maxPathDown(TreeNode* node) {
if (node == nullptr) return 0;
int left = max(0, maxPathDown(node->left));
int right = max(0, maxPathDown(node->right));
return node->val + [1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Adding both left and right sums instead of choosing the maximum.
Using min instead of max.
Not handling negative sums by max with 0.
✗ Incorrect
We want the maximum path sum starting from the current node going down one side, so we add the node's value to the maximum of left or right child sums.
2fill in blank
mediumComplete the code to update the global maximum path sum including the current node and both children.
DSA C++
int maxSum = INT_MIN;
int maxPathDown(TreeNode* node) {
if (node == nullptr) return 0;
int left = max(0, maxPathDown(node->left));
int right = max(0, maxPathDown(node->right));
maxSum = max(maxSum, node->val + [1]);
return node->val + max(left, right);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication instead of addition.
Using only one child sum instead of both.
Using min instead of max.
✗ Incorrect
The maximum path sum through the current node includes the node's value plus both left and right child sums.
3fill in blank
hardFix the error in the base case to correctly handle null nodes.
DSA C++
int maxPathDown(TreeNode* node) {
if (node == [1]) return 0;
int left = max(0, maxPathDown(node->left));
int right = max(0, maxPathDown(node->right));
maxSum = max(maxSum, node->val + left + right);
return node->val + max(left, right);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 or false instead of nullptr.
Using NULL which is legacy in modern C++.
✗ Incorrect
In C++, the correct way to check for a null pointer is 'nullptr'.
4fill in blank
hardFill both blanks to complete the function that returns the maximum path sum in the tree.
DSA C++
int maxPathSum(TreeNode* root) {
maxSum = INT_MIN;
[1](root);
return [2];
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning root instead of maxSum.
Calling maxPathSum recursively instead of maxPathDown.
✗ Incorrect
We call maxPathDown to compute max sums and then return the global maxSum.
5fill in blank
hardFill all three blanks to complete the recursive function that updates maxSum and returns the max path sum down one side.
DSA C++
int maxPathDown(TreeNode* node) {
if (node == nullptr) return 0;
int left = max(0, [1](node->left));
int right = max(0, [2](node->right));
maxSum = max(maxSum, node->val + left + right);
return node->val + [3](left, right);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using min instead of max for choosing child path.
Returning maxSum instead of node value plus max child sum.
Calling wrong function names.
✗ Incorrect
We recursively call maxPathDown on children, update maxSum, and return node value plus max of left and right.
