Bird
Raised Fist0
DSA C++programming~20 mins

DP on Trees Maximum Path Sum in DSA C++ - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
DP on Trees Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Maximum Path Sum in a Simple Binary Tree
What is the output of the following C++ code that calculates the maximum path sum in a binary tree?
DSA C++
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

int maxSum = INT_MIN;

int maxPathSumUtil(TreeNode* root) {
    if (!root) return 0;
    int left = max(0, maxPathSumUtil(root->left));
    int right = max(0, maxPathSumUtil(root->right));
    maxSum = max(maxSum, root->val + left + right);
    return root->val + max(left, right);
}

int maxPathSum(TreeNode* root) {
    maxSum = INT_MIN;
    maxPathSumUtil(root);
    return maxSum;
}

int main() {
    TreeNode* root = new TreeNode(1);
    root->left = new TreeNode(2);
    root->right = new TreeNode(3);
    int result = maxPathSum(root);
    std::cout << result << std::endl;
    return 0;
}
A6
B3
C5
D1
Attempts:
2 left
💡 Hint
Consider the path that includes both left and right children plus the root.
❓ Predict Output
intermediate
2:00remaining
Maximum Path Sum with Negative Values
What is the output of the following C++ code when the tree contains negative values?
DSA C++
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

int maxSum = INT_MIN;

int maxPathSumUtil(TreeNode* root) {
    if (!root) return 0;
    int left = max(0, maxPathSumUtil(root->left));
    int right = max(0, maxPathSumUtil(root->right));
    maxSum = max(maxSum, root->val + left + right);
    return root->val + max(left, right);
}

int maxPathSum(TreeNode* root) {
    maxSum = INT_MIN;
    maxPathSumUtil(root);
    return maxSum;
}

int main() {
    TreeNode* root = new TreeNode(-10);
    root->left = new TreeNode(9);
    root->right = new TreeNode(20);
    root->right->left = new TreeNode(15);
    root->right->right = new TreeNode(7);
    int result = maxPathSum(root);
    std::cout << result << std::endl;
    return 0;
}
A27
B35
C20
D42
Attempts:
2 left
💡 Hint
The maximum path includes nodes 15, 20, and 7.
🔧 Debug
advanced
2:00remaining
Identify the Runtime Error in Maximum Path Sum Code
The following code is intended to find the maximum path sum in a binary tree but causes a runtime error. What is the cause?
DSA C++
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

int maxSum = INT_MIN;

int maxPathSumUtil(TreeNode* root) {
    if (root == nullptr) return 0;
    int left = maxPathSumUtil(root->left);
    int right = maxPathSumUtil(root->right);
    maxSum = max(maxSum, root->val + left + right);
    return root->val + max(left, right);
}

int maxPathSum(TreeNode* root) {
    maxSum = INT_MIN;
    maxPathSumUtil(root);
    return maxSum;
}

int main() {
    TreeNode* root = new TreeNode(-3);
    int result = maxPathSum(root);
    std::cout << result << std::endl;
    return 0;
}
AThe code causes a runtime error because max() is used without including <algorithm> header.
BThe code causes a stack overflow due to infinite recursion.
CThe code does not handle negative path sums properly, causing incorrect maxSum updates.
DThe code causes a runtime error because it returns negative values from maxPathSumUtil.
Attempts:
2 left
💡 Hint
Consider how negative values affect the path sums and the maxSum variable.
🧠 Conceptual
advanced
2:00remaining
Understanding the Role of max(0, ... ) in DP on Trees Maximum Path Sum
Why do we use max(0, maxPathSumUtil(child)) when calculating the maximum path sum in a binary tree?
ATo ensure the function always returns a positive value for the path sum.
BTo ignore negative path sums from child nodes so they don't reduce the total path sum.
CTo avoid null pointer exceptions when child nodes are missing.
DTo prioritize the left subtree over the right subtree in the path sum calculation.
Attempts:
2 left
💡 Hint
Think about what happens if a subtree has a negative sum.
🚀 Application
expert
3:00remaining
Maximum Path Sum in a Tree with Multiple Branches (N-ary Tree)
Given the following code snippet for an N-ary tree, what is the output of the maximum path sum calculation?
DSA C++
struct Node {
    int val;
    std::vector<Node*> children;
    Node(int x) : val(x) {}
};

int maxSum = INT_MIN;

int maxPathSumUtil(Node* root) {
    if (!root) return 0;
    int max1 = 0, max2 = 0;
    for (auto child : root->children) {
        int val = maxPathSumUtil(child);
        if (val > max1) {
            max2 = max1;
            max1 = val;
        } else if (val > max2) {
            max2 = val;
        }
    }
    maxSum = std::max(maxSum, root->val + max1 + max2);
    return root->val + max1;
}

int maxPathSum(Node* root) {
    maxSum = INT_MIN;
    maxPathSumUtil(root);
    return maxSum;
}

int main() {
    Node* root = new Node(10);
    Node* c1 = new Node(2);
    Node* c2 = new Node(10);
    Node* c3 = new Node(20);
    Node* c4 = new Node(1);
    Node* c5 = new Node(-25);
    Node* c6 = new Node(3);
    Node* c7 = new Node(4);

    root->children = {c1, c2, c5};
    c5->children = {c6, c7};
    c2->children = {c3, c4};

    int result = maxPathSum(root);
    std::cout << result << std::endl;
    return 0;
}
A48
B42
C50
D55
Attempts:
2 left
💡 Hint
Consider the two highest child path sums at each node to form the maximum path through that node.

Practice

(1/5)
1. What does the "Maximum Path Sum" in a tree represent in the context of dynamic programming on trees?
easy
A. The largest sum of node values on any path between two nodes in the tree
B. The sum of all node values in the tree
C. The maximum value of a single node in the tree
D. The longest path length in the tree

Solution

  1. Step 1: Understand the problem definition

    The maximum path sum is the highest sum of values collected by traveling along any path between two nodes in the tree, not necessarily passing through the root.
  2. Step 2: Differentiate from other sums

    It is not the sum of all nodes or just the maximum node value, but the maximum sum along any connected path.
  3. Final Answer:

    The largest sum of node values on any path between two nodes in the tree -> Option A
  4. Quick Check:

    Maximum path sum = largest sum on any node-to-node path [OK]
Hint: Maximum path sum is about any path, not whole tree sum [OK]
Common Mistakes:
  • Confusing maximum path sum with total sum of all nodes
  • Thinking it is the maximum single node value
  • Assuming path must start at root
2. Which of the following C++ function signatures is correct for a recursive function that computes the maximum path sum in a binary tree node structure defined as struct TreeNode { int val; TreeNode* left; TreeNode* right; };?
easy
A. int maxPathSum(TreeNode root);
B. void maxPathSum(TreeNode root);
C. int maxPathSum(TreeNode* root);
D. int maxPathSum(TreeNode* root, int sum);

Solution

  1. Step 1: Check parameter passing

    The tree nodes should be passed as pointers to avoid copying the entire subtree, so TreeNode* is correct.
  2. Step 2: Check return type and parameters

    The function returns an integer representing the maximum path sum, so int return type is correct. Additional parameters like int sum are not necessary for the main function signature.
  3. Final Answer:

    int maxPathSum(TreeNode* root); -> Option C
  4. Quick Check:

    Use pointer parameter and int return type [OK]
Hint: Use pointer parameter and int return type for tree recursion [OK]
Common Mistakes:
  • Passing TreeNode by value causing copies
  • Using void return type when int is needed
  • Adding unnecessary parameters in main signature
3. Consider the following C++ code snippet for maximum path sum in a binary tree:
struct TreeNode { int val; TreeNode* left; TreeNode* right; };

int maxSum = INT_MIN;

int dfs(TreeNode* node) {
  if (!node) return 0;
  int left = max(0, dfs(node->left));
  int right = max(0, dfs(node->right));
  maxSum = max(maxSum, node->val + left + right);
  return node->val + max(left, right);
}

int maxPathSum(TreeNode* root) {
  dfs(root);
  return maxSum;
}

// Tree structure:
//       1
//      / \
//     2   3
//
// What is the output of maxPathSum(root)?
medium
A. 5
B. 6
C. 3
D. 1

Solution

  1. Step 1: Calculate dfs values for each node

    For leaf nodes 2 and 3, dfs returns their values (2 and 3). For root 1, left=2, right=3, so maxSum = max(INT_MIN, 1+2+3) = 6.
  2. Step 2: Return maxSum after dfs completes

    The function returns maxSum = 6, which is the maximum path sum (2 -> 1 -> 3).
  3. Final Answer:

    6 -> Option B
  4. Quick Check:

    Max path sum = 2 + 1 + 3 = 6 [OK]
Hint: Add node value plus max left and right sums, ignore negatives [OK]
Common Mistakes:
  • Ignoring max(0, dfs(...)) causing negative sums
  • Returning node->val + left + right instead of max path
  • Confusing maxSum update with return value
4. The following code attempts to compute the maximum path sum in a binary tree but has a bug:
int maxSum = INT_MIN;

int dfs(TreeNode* node) {
  if (!node) return 0;
  int left = dfs(node->left);
  int right = dfs(node->right);
  maxSum = max(maxSum, node->val + left + right);
  return node->val + max(left, right);
}

What is the main issue causing incorrect results?
medium
A. It does not handle null nodes properly
B. It returns the sum of both children instead of max
C. It does not update maxSum correctly
D. It does not ignore negative sums from children

Solution

  1. Step 1: Analyze child sums usage

    The code uses raw dfs values for left and right without ignoring negative sums, which can reduce the path sum.
  2. Step 2: Identify fix for negative sums

    To fix, use max(0, dfs(...)) to ignore negative sums from children, ensuring path sum only increases or stays same.
  3. Final Answer:

    It does not ignore negative sums from children -> Option D
  4. Quick Check:

    Use max(0, dfs(child)) to avoid negative sums [OK]
Hint: Always ignore negative child sums with max(0, dfs(child)) [OK]
Common Mistakes:
  • Not using max(0, ...) causing negative path sums
  • Returning sum of both children instead of max for recursion
  • Incorrect maxSum update logic
5. Given a binary tree where nodes can have negative values, how would you modify the standard maximum path sum algorithm to correctly handle the case where the maximum path sum is a single node with a negative value? Choose the best approach.
hard
A. Initialize maxSum with INT_MIN and use max(0, dfs(child)) in recursion
B. Initialize maxSum with 0 and ignore negative node values completely
C. Initialize maxSum with INT_MIN and allow dfs to return negative values without max(0, ...)
D. Initialize maxSum with 0 and always add node values regardless of sign

Solution

  1. Step 1: Recall the standard algorithm

    The standard algorithm initializes maxSum to INT_MIN and uses left = max(0, dfs(left)), right = max(0, dfs(right)), updating maxSum = max(maxSum, node.val + left + right). This captures single negative nodes as node.val + 0 + 0.
  2. Step 2: Why it handles negatives

    max(0, dfs(child)) prevents extending to negative subtrees but allows dfs to return node.val + 0 (negative if node negative). INT_MIN init captures negative maxima.
  3. Step 3: Why A fails

    Without max(0, ...), negative child sums pollute parent updates (e.g., root=-2, left=-3: maxSum wrongly stays -3 instead of -2).
  4. Final Answer:

    Initialize maxSum with INT_MIN and use max(0, dfs(child)) in recursion -> Option A
  5. Quick Check:

    max(0, dfs(child)) + INT_MIN handles negative single nodes [OK]
Hint: Standard max(0, dfs(child)) + INT_MIN handles negative nodes correctly [OK]
Common Mistakes:
  • Omitting max(0, ...) letting negative children reduce parent path sums
  • Initializing maxSum with 0 missing negative maxima
  • Ignoring all negative nodes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard