DP on Trees Maximum Path Sum in DSA C# - 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.
public int MaxPathSum(TreeNode root) {
int maxSum = int.MinValue;
int DFS(TreeNode node) {
if (node == null) return 0;
int left = Math.Max(0, DFS(node.left));
int right = Math.Max(0, DFS(node.right));
maxSum = Math.Max(maxSum, left + right + node.val);
return Math.Max(left, right) + node.val;
}
DFS(root);
return maxSum;
}
This code finds the maximum sum of values along any path in a binary tree using a depth-first search.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls visiting each node once.
- How many times: Each node is visited exactly one time during the DFS traversal.
As the number of nodes increases, the number of steps grows roughly the same as the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The steps grow linearly with the number of nodes.
Time Complexity: O(n)
This means the time to find the maximum path sum grows directly in proportion to the number of nodes in the tree.
[X] Wrong: "The recursion visits nodes multiple times, so the time is more than linear."
[OK] Correct: Each node is visited once, and results are combined on the way back, so no repeated work happens.
Understanding this linear time complexity helps you explain how efficient tree traversals with dynamic programming work in real problems.
"What if we changed the tree to a graph with cycles? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem definition
The maximum path sum means the highest total sum of node values collected along any path connecting two nodes in the tree, not necessarily passing through the root.Step 2: Differentiate from other sums
It is not the sum of all nodes or just the maximum single node value, but the sum along a path that can include multiple nodes.Final Answer:
The largest sum of node values on any path between two nodes in the tree -> Option BQuick Check:
Maximum path sum = largest node value sum on any path [OK]
- Confusing maximum path sum with sum of all nodes
- Thinking it is just the maximum node value
- Assuming path must start at root
Solution
Step 1: Identify the return type needed
The function should return an integer representing the maximum path sum starting from the given node.Step 2: Check parameter type
The parameter must be a TreeNode object to access node values and children.Final Answer:
int MaxPathSum(TreeNode node) -> Option AQuick Check:
Return type int and parameter TreeNode required [OK]
- Using void return type when int is needed
- Passing int instead of TreeNode as parameter
- Returning TreeNode instead of int
public class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int x) { val = x; }
}
int maxSum = int.MinValue;
int MaxPathSum(TreeNode node) {
if (node == null) return 0;
int left = Math.Max(0, MaxPathSum(node.left));
int right = Math.Max(0, MaxPathSum(node.right));
maxSum = Math.Max(maxSum, left + right + node.val);
return Math.Max(left, right) + node.val;
}
// Tree structure:
// 1
// / \
// 2 3
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
MaxPathSum(root);
Console.WriteLine(maxSum);
What is the output printed?Solution
Step 1: Calculate max path sums for children
For node 2 and 3, left and right children are null, so returns 0. Max path sum at node 2 and 3 is their own value (2 and 3).Step 2: Calculate max path sum at root
At root (1), left = max(0, 2) = 2, right = max(0, 3) = 3. maxSum updated to max(-∞, 2+3+1) = 6. Return max(2,3)+1=4.Final Answer:
6 -> Option DQuick Check:
Sum of path 2->1->3 = 6 [OK]
- Ignoring max(0, child) and using negative sums
- Returning sum without updating maxSum
- Confusing return value with maxSum
int maxSum = int.MinValue;
int MaxPathSum(TreeNode node) {
if (node == null) return 0;
int left = MaxPathSum(node.left);
int right = MaxPathSum(node.right);
maxSum = Math.Max(maxSum, left + right + node.val);
return Math.Max(left, right) + node.val;
}
What is the bug in this code?Solution
Step 1: Analyze child sums usage
The code uses left and right sums directly without ignoring negative values, which can reduce the path sum.Step 2: Identify fix for negative sums
We must use Math.Max(0, left) and Math.Max(0, right) to ignore negative sums from children.Final Answer:
It does not ignore negative sums from children -> Option AQuick Check:
Negative child sums must be ignored [OK]
- Not using Math.Max(0, child) causing wrong sums
- Assuming return type is wrong
- Missing null checks (which are present)
Solution
Step 1: Understand the correct DP approach
The correct approach is to consider the maximum path sum including both children and update a global max, returning the max path sum including one child plus node value.Step 2: Identify the incorrect options
The other options do not correctly handle the problem. They either sum all children, return only the maximum child value, or ignore children and consider only node value.Final Answer:
Compute max path sum including both children and update global max; return max path sum including one child plus node value -> Option CQuick Check:
Correct DP uses both children sums and global max update [OK]
- Ignoring children nodes in calculation
- Summing all children without max checks
- Returning only child values without node
Ready to prove it?
Pass the test and this pattern moves unknown
