📖 Scenario: You are working with a tree data structure representing a network of connected nodes. Each node has a value that can be positive or negative. You want to find the maximum sum of values along any path in the tree. A path can start and end at any nodes but must follow the tree connections without revisiting nodes.
🎯 Goal: Build a TypeScript program that uses dynamic programming on trees to find the maximum path sum. You will create the tree, set up a helper variable, write the core recursive function to compute the maximum path sum, and finally print the result.
📋 What You'll Learn
Create a tree using a Node class with value and children properties
Use a helper variable to track the maximum path sum found so far
Implement a recursive function to compute maximum path sums using dynamic programming
Print the maximum path sum after processing the tree
💡 Why This Matters
🌍 Real World
Finding maximum path sums in trees is useful in network analysis, decision trees, and hierarchical data processing where you want to find the most valuable route or connection.
💼 Career
This problem teaches recursion, dynamic programming on trees, and handling complex data structures, which are common in software engineering interviews and real-world algorithmic challenges.
Progress0 / 4 steps
1
Create the tree nodes and structure
Create a class called Node with a constructor that takes a value (number) and initializes a children array. Then create the following nodes with these exact values: root with value 10, nodeA with value 2, nodeB with value 10, nodeC with value 20, nodeD with value 1, and nodeE with value -25. Connect the nodes to form this tree structure: root has children nodeA and nodeB; nodeB has children nodeC and nodeD; nodeD has child nodeE.
DSA Typescript
Hint
Define the Node class first. Then create each node with the exact values. Finally, connect children using the children.push() method.
2
Add a helper variable to track maximum path sum
Create a variable called maxSum and initialize it to Number.NEGATIVE_INFINITY. This will keep track of the highest path sum found during recursion.
DSA Typescript
Hint
Use let maxSum = Number.NEGATIVE_INFINITY to start with the smallest possible number.
3
Implement recursive function to find maximum path sum
Write a function called maxPathSumHelper that takes a node of type Node and returns a number. Inside, recursively compute the maximum path sum for each child. Use these steps: 1) For each child, call maxPathSumHelper(child) and store the results in an array. 2) Find the top two maximum values from these results or use 0 if none are positive. 3) Calculate the current maximum path sum as node.value + max1 + max2. 4) Update maxSum if this current sum is greater. 5) Return node.value + max1 as the maximum sum path starting from this node going down one branch.
DSA Typescript
Hint
Use recursion to get sums from children. Sort to find top two positive sums. Update maxSum if current path sum is bigger. Return the max sum path starting from this node.
4
Print the maximum path sum result
Call maxPathSumHelper(root) to process the tree. Then print the value of maxSum using console.log(maxSum).
DSA Typescript
Hint
Call the helper function with root and then print maxSum to see the maximum path sum.
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 sum of all node values in the tree
B. The largest sum of node values along any path between two nodes in the tree
C. The maximum value of a single node in the tree
D. The longest path length in the tree
Solution
Step 1: Understand the problem definition
The maximum path sum is about finding the path between any two nodes that yields the highest sum of node values.
Step 2: Differentiate from other sums
It is not the sum of all nodes or just the max node value, but the max sum along a connected path.
Final Answer:
The largest sum of node values along any path between two nodes in the tree -> Option B
Quick Check:
Maximum path sum = max sum on any path [OK]
Hint: Maximum path sum is about any path, not whole tree sum [OK]
Common Mistakes:
Confusing maximum path sum with sum of all nodes
Thinking it is just the max node value
Assuming path must start at root
2. Which of the following TypeScript function signatures correctly represents a recursive function to find maximum path sum in a binary tree node?
easy
A. function maxPathSum(node: TreeNode): void
B. function maxPathSum(node: number): number
C. function maxPathSum(): number
D. function maxPathSum(node: TreeNode | null): number
Solution
Step 1: Check parameter type
The function must accept a TreeNode or null to handle empty nodes.
Step 2: Check return type
It should return a number representing the max path sum from that node.
Final Answer:
function maxPathSum(node: TreeNode | null): number -> Option D
Quick Check:
Correct parameter and return type [OK]
Hint: Function must accept node or null and return number [OK]
Common Mistakes:
Using wrong parameter type (e.g., number instead of TreeNode)
Returning void instead of number
Not allowing null for leaf children
3. Consider the following TypeScript code snippet for maximum path sum in a binary tree:
class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function maxPathSum(root: TreeNode | null): number {
let maxSum = -Infinity;
function dfs(node: TreeNode | null): number {
if (!node) return 0;
const left = Math.max(dfs(node.left), 0);
const 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 tree = new TreeNode(1, new TreeNode(2), new TreeNode(3));
console.log(maxPathSum(tree));
What is the output of this code?
medium
A. 3
B. 5
C. 6
D. 1
Solution
Step 1: Trace DFS on tree nodes
For node 2 and 3, max path sums are 2 and 3 respectively. For root 1, left=2, right=3.
Step 2: Calculate maxSum updates
maxSum updates to max(-Infinity, 1+2+3) = 6. Return value for root is 1 + max(2,3) = 4 but maxSum remains 6.
Final Answer:
6 -> Option C
Quick Check:
Sum of path 2->1->3 = 6 [OK]
Hint: Sum left + node + right for max path sum [OK]
Common Mistakes:
Returning max path from root only, ignoring subtrees
Not using Math.max with 0 to ignore negative sums
Confusing return value with maxSum global
4. The following TypeScript code attempts to find the maximum path sum in a binary tree but has a bug:
function maxPathSum(root: TreeNode | null): number {
let maxSum = -Infinity;
function dfs(node: TreeNode | null): number {
if (!node) return 0;
const left = dfs(node.left);
const right = dfs(node.right);
maxSum = Math.max(maxSum, node.val + left + right);
return node.val + Math.max(left, right);
}
dfs(root);
return maxSum;
}
What is the bug in this code?
medium
A. It does not ignore negative sums from left or right subtree
B. It returns void instead of number
C. It does not handle null root
D. It uses global variable incorrectly
Solution
Step 1: Analyze subtree sums usage
The code uses left and right sums directly without ignoring negative values.
Step 2: Identify impact on maxSum
Negative sums can reduce maxSum, so we must use Math.max(dfs(...), 0) to ignore negatives.
Final Answer:
It does not ignore negative sums from left or right subtree -> Option A
Quick Check:
Negative subtree sums must be ignored [OK]
Hint: Use Math.max(dfs(...), 0) to ignore negatives [OK]
Common Mistakes:
Not checking for negative subtree sums
Assuming dfs returns void
Ignoring null root case
5. Given a binary tree where some nodes have negative values, how would you modify the dynamic programming approach to find the maximum path sum that can start and end at any node, but the path must go downwards (only from parent to child)?
hard
A. Use DFS to compute max downward path sum at each node ignoring negative sums by max(0, childSum)
B. Use BFS to find the longest path ignoring node values
C. Sum all node values and subtract minimum node value
D. Only consider paths that include the root node
Solution
Step 1: Understand downward path constraint
The path must go downwards from parent to child, so use DFS to explore children.
Step 2: Handle negative values
Ignore negative sums by taking max(0, childSum) to avoid reducing path sum.
Step 3: Calculate max path sum
At each node, max downward path sum = node.val + max(leftChildSum, rightChildSum, 0).
Final Answer:
Use DFS to compute max downward path sum at each node ignoring negative sums by max(0, childSum) -> Option A