Bird
Raised Fist0
DSA Javascriptprogramming~30 mins

Maximum Path Sum in Binary Tree in DSA Javascript - Build from Scratch

Choose your learning style10 modes available
Maximum Path Sum in Binary Tree
๐Ÿ“– Scenario: You are working on a system that analyzes decision trees. Each node in the tree has a value representing a score. You want to find the maximum sum of values along any path in the tree. A path can start and end at any node, but it must follow parent-child connections.
๐ŸŽฏ Goal: Build a program that finds the maximum path sum in a binary tree. You will create the tree nodes, set up a helper variable, write the function to find the maximum path sum, and print the result.
๐Ÿ“‹ What You'll Learn
Create a binary tree with the exact structure and values given
Create a variable to track the maximum path sum
Write a recursive function called maxPathSumHelper that calculates the maximum path sum
Print the maximum path sum after processing the tree
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
Finding maximum path sums in trees is useful in decision-making systems, network analysis, and game AI where paths represent choices or routes.
๐Ÿ’ผ Career
Understanding tree traversal and recursion is essential for software engineers working on algorithms, data processing, and system design.
Progress0 / 4 steps
1
Create the Binary Tree Nodes
Create a class called TreeNode with a constructor that takes val, left, and right. Then create the binary tree with root node value 1, left child 2, and right child 3. Assign the root node to a variable called root.
DSA Javascript
Hint

Define the TreeNode class with a constructor that sets val, left, and right. Then create the root node with value 1 and children 2 and 3.

2
Create a Variable to Track Maximum Path Sum
Create a variable called maxSum and set it to Number.NEGATIVE_INFINITY to track the maximum path sum found so far.
DSA Javascript
Hint

Use let maxSum = Number.NEGATIVE_INFINITY; to start tracking the maximum path sum.

3
Write the Recursive Function to Find Maximum Path Sum
Write a function called maxPathSumHelper that takes a node as input. It should return the maximum path sum starting from that node going down. Update maxSum with the maximum path sum found including the current node and both children. Use recursion to get left and right maximum sums. Return the maximum path sum including the current node and one child or none.
DSA Javascript
Hint

Use recursion to get maximum sums from left and right children. Ignore negative sums by using Math.max(0, ...). Update maxSum with the sum including both children and current node. Return the max path sum including current node and one child.

4
Print the Maximum Path Sum
Call maxPathSumHelper with root and then print the value of maxSum.
DSA Javascript
Hint

Call maxPathSumHelper(root) to start the recursion. Then print maxSum to see the maximum path sum.

Practice

(1/5)
1. What does the "Maximum Path Sum in Binary Tree" problem ask you to find?
easy
A. The sum of all node values in the tree
B. The longest path length in the binary tree
C. The highest sum of values along any path between two nodes in the tree
D. The maximum value of a single node in the tree

Solution

  1. Step 1: Understand the problem definition

    The problem asks for the maximum sum of node values along any path in the binary tree. A path can start and end at any nodes, but must be connected.
  2. Step 2: Differentiate from other path problems

    This is not about longest path length or total sum of all nodes, but the maximum sum of values on any path.
  3. Final Answer:

    The highest sum of values along any path between two nodes in the tree -> Option C
  4. Quick Check:

    Maximum path sum = highest sum path [OK]
Hint: Focus on sum of connected nodes, not length or single node [OK]
Common Mistakes:
  • Confusing maximum path sum with longest path length
  • Thinking path must start at root
  • Summing all nodes instead of a path
2. Which of the following is the correct base case return value for a recursive function computing maximum path sum in a binary tree node when the node is null?
easy
A. -Infinity
B. 1
C. null
D. 0

Solution

  1. Step 1: Consider the meaning of base case for null node

    When the node is null, the maximum gain from this subtree is 0 (choose not to extend path here).
  2. Step 2: Why not others?

    -Infinity works only with Math.max(0, result) but 0 is standard and cleaner. Returning 0 allows proper clamping in parent. null or 1 cause type/math errors.
  3. Final Answer:

    0 -> Option D
  4. Quick Check:

    Base case for null = 0 [OK]
Hint: Return 0 for null to represent zero contribution [OK]
Common Mistakes:
  • Returning -Infinity without Math.max(0, ยท)
  • Returning null causing type errors
  • Returning positive values skewing max
3. What is the output of the following code snippet for maximum path sum?
class TreeNode {
  constructor(val, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

function maxPathSum(root) {
  let maxSum = -Infinity;
  function dfs(node) {
    if (!node) return 0;
    let left = Math.max(dfs(node.left), 0);
    let right = Math.max(dfs(node.right), 0);
    maxSum = Math.max(maxSum, node.val + left + right);
    return node.val + Math.max(left, right);
  }
  dfs(root);
  return maxSum;
}

const root = new TreeNode(-10, new TreeNode(9), new TreeNode(20, new TreeNode(15), new TreeNode(7)));
console.log(maxPathSum(root));
medium
A. 42
B. 35
C. 27
D. 20

Solution

  1. Step 1: Trace dfs on left subtree

    Left child 9: left=0, right=0, maxSum = 9, returns 9.
  2. Step 2: Trace dfs on right subtree

    dfs(15)=15 updates maxSum=15; dfs(7)=7 keeps 15; at 20: left=15, right=7, maxSum = max(15, 20+15+7=42)=42, returns 20+15=35.
  3. Step 3: Calculate root node max sum

    Root: left=9, right=35, path sum -10+9+35=34 <42, maxSum remains 42.
  4. Final Answer:

    42 -> Option A
  5. Quick Check:

    Max path sum = 42 [OK]
Hint: Add node + max(left, right) and update maxSum with both sides [OK]
Common Mistakes:
  • Not ignoring negative sums by using Math.max with 0
  • Adding left and right children incorrectly
  • Confusing return value with maxSum update
4. Identify the bug in this maximum path sum function and select the fix:
function maxPathSum(root) {
  let maxSum = -Infinity;
  function dfs(node) {
    if (!node) return -Infinity;
    let left = dfs(node.left);
    let right = dfs(node.right);
    maxSum = Math.max(maxSum, node.val + left + right);
    return node.val + Math.max(left, right);
  }
  dfs(root);
  return maxSum;
}
medium
A. Add check to ignore negative sums with Math.max(left, 0)
B. Change base case return from -Infinity to 0
C. Initialize maxSum to 0 instead of -Infinity
D. Return maxSum inside dfs instead of outside

Solution

  1. Step 1: Analyze base case and recursive calls

    Returning -Infinity for null nodes causes left and right to be -Infinity, which breaks addition and max calculations.
  2. Step 2: Fix by ignoring negative sums

    Use Math.max(dfs(node.left), 0) and Math.max(dfs(node.right), 0) to ignore negative paths and avoid incorrect sums.
  3. Final Answer:

    Add check to ignore negative sums with Math.max(left, 0) -> Option A
  4. Quick Check:

    Ignore negative sums with Math.max(..., 0) [OK]
Hint: Ignore negative child sums by max with 0 to fix bugs [OK]
Common Mistakes:
  • Returning -Infinity breaks addition
  • Not ignoring negative sums from children
  • Changing maxSum initialization wrongly
5. Given a binary tree where some nodes have negative values, how would you modify the maximum path sum algorithm to handle the case where all values are negative?
hard
A. Allow paths to be empty and return 0 if all sums are negative
B. Track the maximum single node value separately and compare with path sums
C. Use Math.max with 0 on child sums to ignore negatives
D. Initialize maxSum to -Infinity and do not ignore negative child sums

Solution

  1. Step 1: Understand all-negative case

    The max path sum is the highest (least negative) single node value. Paths must include at least one node.
  2. Step 2: Key modification

    Tracking the maximum single node value separately ensures that if all child sums are negative, the algorithm still returns the maximum node value. Using Math.max(0, dfs(child)) ignores negative child sums but can miss the max single node if all are negative.
  3. Final Answer:

    Track the maximum single node value separately and compare with path sums -> Option B
  4. Quick Check:

    Separate max node tracking handles all-negative correctly [OK]
Hint: Track max single node separately to handle all-negative cases [OK]
Common Mistakes:
  • Allowing empty path return 0 (invalid)
  • Not tracking max node separately (misses max negative node)
  • Not ignoring negative child sums (misses single 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