Maximum Path Sum in Binary Tree in DSA Go - Time & Space Complexity
We want to understand 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.
func maxPathSum(root *TreeNode) int {
maxSum := math.MinInt32
var dfs func(node *TreeNode) int
dfs = func(node *TreeNode) int {
if node == nil {
return 0
}
left := max(0, dfs(node.Left))
right := max(0, dfs(node.Right))
maxSum = max(maxSum, left + right + node.Val)
return max(left, right) + node.Val
}
dfs(root)
return maxSum
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
This code finds the maximum sum of any path in a binary tree by visiting each node once and calculating sums from its children.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive depth-first search (dfs) visits each node once.
- How many times: Exactly once per node in the tree.
Each node is visited once, so the total steps grow directly 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 tree size increases.
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 the time is more than linear."
[OK] Correct: Each node is visited once, and results from children are reused immediately, so no repeated work happens.
Understanding this linear time complexity helps you explain why your solution is efficient and suitable for large trees, a skill valued in interviews.
"What if the tree was a linked list (all nodes have only one child)? How would the time complexity change?"