0
0
DSA Goprogramming~5 mins

Maximum Path Sum in Binary Tree in DSA Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Maximum Path Sum in Binary Tree
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each node is visited once, so the total steps grow directly with the number of nodes.

Input Size (n)Approx. Operations
10About 10 visits
100About 100 visits
1000About 1000 visits

Pattern observation: The work grows linearly as the tree size increases.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding this linear time complexity helps you explain why your solution is efficient and suitable for large trees, a skill valued in interviews.

Self-Check

"What if the tree was a linked list (all nodes have only one child)? How would the time complexity change?"