DP on Trees Maximum Path Sum in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to find the maximum path sum in a tree grows as the tree gets bigger.
How does the number of steps change when the tree has more nodes?
Analyze the time complexity of the following code snippet.
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;
}
This code finds the maximum sum of values along any path in a binary tree using a depth-first search.
- Primary operation: Recursive depth-first search visiting each node once.
- How many times: Each node is visited exactly one time.
As the number of nodes in the tree grows, the number of steps grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The work grows linearly with the number of nodes.
Time Complexity: O(n)
This means the time to find the maximum path sum grows in direct proportion to the number of nodes in the tree.
[X] Wrong: "The recursion visits nodes multiple times, so time is more than linear."
[OK] Correct: Each node is visited once because the recursion returns results up the tree without revisiting nodes.
Understanding this time complexity helps you explain how efficient your tree algorithms are, a key skill in many coding challenges.
"What if we changed the tree to a graph with cycles? How would the time complexity change?"
Practice
Maximum path sum means:Solution
Step 1: Understand the path definition
A path in a tree is any sequence of nodes connected by edges, not necessarily starting at the root.Step 2: Define maximum path sum meaning
The maximum path sum is the highest total value you get by adding node values along any such path.Final Answer:
The largest sum of node values along any path in the tree -> Option AQuick Check:
Maximum path sum = largest node value sum [OK]
- Confusing path length with sum
- Thinking path must start at root
- Choosing sum of all nodes instead of max path
function maxPathSum(node) {
if (___) return 0;
// rest of code
}Solution
Step 1: Identify when recursion should stop
When the node is empty (null), there is no path, so return 0.Step 2: Check options for base case
Only checking if node is null correctly handles leaf children and empty trees.Final Answer:
node === null -> Option CQuick Check:
Base case: node null means no path [OK]
- Using node.value === 0 which is incorrect
- Checking both children null instead of node null
- Using node === undefined which is less common
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 === null) 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 tree = new TreeNode(1, new TreeNode(2), new TreeNode(3));
console.log(maxPathSum(tree));Solution
Step 1: Calculate max path sums for each node
For leaf nodes 2 and 3, max path sum is their value (2 and 3). For root 1, left=2, right=3, sum=1+2+3=6.Step 2: Update maxSum and return correct values
maxSum updates to 6 at root. Return values propagate correctly.Final Answer:
6 -> Option AQuick Check:
Sum of 1+2+3 = 6 [OK]
- Forgetting to ignore negative sums
- Returning node.val + left + right instead of max(left, right)
- Confusing maxSum update with return value
function maxPathSum(root) {
let maxSum = -Infinity;
function dfs(node) {
if (!node) return 0;
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;
}Solution
Step 1: Check handling of negative child sums
The code uses left = dfs(node.left) directly without ignoring negatives, which can reduce maxSum incorrectly.Step 2: Correct approach to ignore negatives
Should use left = Math.max(dfs(node.left), 0) and similarly for right to avoid negative paths.Final Answer:
It does not ignore negative sums from children -> Option BQuick Check:
Ignore negatives to maximize path sum [OK]
- Not ignoring negative sums
- Returning before dfs call
- Wrong base case check
Choose the best approach:
Solution
Step 1: Understand negative values impact
If all nodes are negative, ignoring negative sums by replacing with 0 would incorrectly return 0 instead of the max negative value.Step 2: Use -Infinity initialization and allow negative sums
Initialize maxSum to -Infinity and do not ignore negative sums completely, so the max negative node is chosen.Final Answer:
Initialize maxSum to -Infinity and allow paths with negative sums -> Option DQuick Check:
Allow negative sums to handle all-negative nodes [OK]
- Ignoring negatives leads to wrong zero result
- Returning 0 when no positive path exists
- Restricting paths to root only
Ready to prove it?
Pass the test and this pattern moves unknown
