Maximum Path Sum in Binary Tree in DSA Python - Time & Space Complexity
We want to know how the time needed to find the maximum path sum in a binary tree grows as the tree gets bigger.
Specifically, how does the number of steps change when the number of nodes increases?
Analyze the time complexity of the following code snippet.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def maxPathSum(root):
max_sum = float('-inf')
def helper(node):
nonlocal max_sum
if not node:
return 0
left = max(helper(node.left), 0)
right = max(helper(node.right), 0)
max_sum = max(max_sum, node.val + left + right)
return node.val + max(left, right)
helper(root)
return max_sum
This code finds the maximum sum of values along any path in a binary tree, where a path can start and end at any nodes.
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 recursion.
As the number of nodes grows, the function visits each node once, so the total steps grow roughly in direct proportion to 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 tree size increases.
Time Complexity: O(n)
This means the time to find the maximum path sum grows directly with 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 very unbalanced and looked like a linked list? How would the time complexity change?"
Practice
Solution
Step 1: Understand the path definition
A path can start and end at any nodes, not necessarily root or leaf.Step 2: Define maximum path sum
It is the highest sum of node values along any such path in the tree.Final Answer:
The largest sum of values along any path between two nodes -> Option BQuick Check:
Maximum path sum = largest sum on any path [OK]
- Thinking path must start at root
- Confusing max node value with max path sum
- Summing all nodes instead of a path
root?Solution
Step 1: Identify input type
The function takes a TreeNode object representing the root of the tree.Step 2: Identify return type
The function returns an integer representing the maximum path sum.Final Answer:
def maxPathSum(root: TreeNode) -> int: -> Option AQuick Check:
Input=TreeNode, Output=int [OK]
- Using int as input instead of TreeNode
- Returning TreeNode instead of int
- Mixing input and output types
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def maxPathSum(root):
max_sum = float('-inf')
def helper(node):
nonlocal max_sum
if not node:
return 0
left = max(helper(node.left), 0)
right = max(helper(node.right), 0)
max_sum = max(max_sum, node.val + left + right)
return node.val + max(left, right)
helper(root)
return max_sum
root = TreeNode(-10, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
print(maxPathSum(root))Solution
Step 1: Trace left and right subtree sums
Left subtree max path sum is 9, right subtree max path sum is 20 + 15 + 7 = 42.Step 2: Calculate max path sum including root
Root (-10) + left (9) + right (20 + 15 + 7) = -10 + 9 + 22 = 21, but max path sum is updated at right subtree as 42.Step 3: Identify maximum path sum
The maximum path sum is 42, but the path that includes root is less than 42.Final Answer:
42 -> Option CQuick Check:
Max path sum = 42 [OK]
- Including negative sums from subtrees
- Confusing return value with max_sum
- Not using nonlocal for max_sum
def maxPathSum(root):
max_sum = float('-inf')
def helper(node):
if not node:
return 0
left = helper(node.left)
right = helper(node.right)
max_sum = max(max_sum, node.val + left + right)
return node.val + max(left, right)
helper(root)
return max_sumSolution
Step 1: Identify variable scope issue
max_sum is assigned inside helper but declared outside, so Python treats it as local inside helper.Step 2: Fix scope with nonlocal keyword
Adding 'nonlocal max_sum' inside helper allows updating the outer max_sum variable.Final Answer:
max_sum should be declared as nonlocal inside helper -> Option AQuick Check:
Use nonlocal to update outer variable [OK]
- Forgetting nonlocal causes UnboundLocalError
- Changing base case return value incorrectly
- Initializing max_sum to 0 misses negative sums
Solution
Step 1: Understand impact of negative values
Negative sums reduce total path sum, so ignoring them improves max sum.Step 2: Use max(child_sum, 0) to ignore negatives
This ensures only positive contributions add to current node's path sum.Step 3: Avoid altering original node values
Replacing negatives with zero changes tree data and is incorrect.Final Answer:
Ignore negative child sums by taking max(child_sum, 0) before adding to current node -> Option DQuick Check:
Ignore negatives with max(child_sum, 0) [OK]
- Adding negative sums reduces max path sum
- Modifying node values instead of sums
- Restricting paths to root-leaf only
Ready to prove it?
Pass the test and this pattern moves unknown
