Maximum Path Sum in Binary Tree in DSA Java - Time & Space Complexity
We want to know how the time needed to find the maximum path sum in a binary tree changes as the tree grows.
How does the number of steps grow when the tree has more nodes?
Analyze the time complexity of the following code snippet.
private int maxSum;
public int maxPathSum(TreeNode root) {
maxSum = Integer.MIN_VALUE;
maxGain(root);
return maxSum;
}
private int maxGain(TreeNode node) {
if (node == null) return 0;
int leftGain = Math.max(maxGain(node.left), 0);
int rightGain = Math.max(maxGain(node.right), 0);
int priceNewPath = node.val + leftGain + rightGain;
maxSum = Math.max(maxSum, priceNewPath);
return node.val + Math.max(leftGain, rightGain);
}
This code finds the maximum sum of any path in a binary tree by checking all possible paths through each node.
- Primary operation: Recursive calls visiting each node once.
- How many times: Each node is visited exactly one time during recursion.
Each node causes a fixed amount of work plus calls to its children. As the tree grows, the total work grows roughly with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The work grows linearly as the number of nodes increases.
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 full visits happen.
Understanding this time complexity helps you explain how efficient your solution is and shows you can analyze recursive tree problems clearly.
"What if the tree was a linked list (all nodes have only one child)? How would the time complexity change?"
Practice
Maximum Path Sum in Binary Tree problem ask you to find?Solution
Step 1: Understand the problem goal
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 node but must be connected.Step 2: Differentiate from other tree metrics
It is not about path length, smallest value, or leaf count. It focuses on sum of node values along a path.Final Answer:
The highest sum of values along any path in the tree -> Option AQuick Check:
Maximum path sum = highest sum of connected nodes [OK]
- Confusing path sum with path length
- Thinking path must start at root
- Ignoring negative values in nodes
TreeNode?Solution
Step 1: Recall Java method syntax
In Java, a method returning an int with public access and a parameter of type TreeNode is declared as:public int maxPathSum(TreeNode root).Step 2: Check other options for syntax errors
Options A, B, and D have invalid syntax: missing return type, misplaced void, or arrow notation not used in Java.Final Answer:
public int maxPathSum(TreeNode root) -> Option BQuick Check:
Java method syntax = public int methodName(Type param) [OK]
- Using arrow notation like other languages
- Mixing return type and void incorrectly
- Omitting access modifier
1 / \ 2 3
What is the maximum path sum?
Solution
Step 1: Identify all possible paths and their sums
Paths and sums: 2 alone = 2, 3 alone = 3, 1 alone = 1, 2->1 = 3, 3->1 = 4, 2->1->3 = 6.Step 2: Find the maximum sum
The maximum sum is 6 from path 2->1->3.Final Answer:
6 -> Option DQuick Check:
Sum(2+1+3) = 6 [OK]
- Ignoring paths that go through root connecting both children
- Only considering single branches
- Adding node values incorrectly
int maxPathSum(TreeNode root) {
if (root == null) return 0;
int left = maxPathSum(root.left);
int right = maxPathSum(root.right);
return Math.max(left, right) + root.val;
}What is the main issue with this code?
Solution
Step 1: Analyze the recursive return value
The code returns the max sum of either left or right subtree plus root value, ignoring the case where path passes through root connecting both sides.Step 2: Understand maximum path sum definition
Maximum path sum can include left subtree + root + right subtree, which this code misses.Final Answer:
It does not consider paths passing through the root connecting left and right -> Option CQuick Check:
Missing combined path sum through root [OK]
- Ignoring combined paths through root
- Assuming max of left/right is enough
- Not updating global max path sum
Solution
Step 1: Understand handling negative values
Negative node values can reduce path sum, so ignore negative gains by comparing with 0 when calculating max gain from children.Step 2: Use recursive helper with global max update
Recursively compute max gain from left and right, update global max with left + node + right, and return max gain for parent calls.Step 3: Reject incorrect approaches
Summing all nodes ignores path constraints, root-to-leaf only misses other paths, BFS longest path ignores sums.Final Answer:
Use a recursive helper that returns max gain from each node, update global max with max of left + node + right, and ignore negative gains by comparing with 0 -> Option AQuick Check:
Recursive max gain + global max update handles negatives [OK]
- Summing all nodes regardless of path
- Only considering root-to-leaf paths
- Not handling negative values properly
Ready to prove it?
Pass the test and this pattern moves unknown
