Graph Theory37 sections · 1633 units
Open in Course

LeetCode 124 Binary Tree Maximum Path Sum - Implementation

Code with global variable

Pseudocode:

maxPath := -infinity

function dfs(v)
    if v is null then
        return 0
    leftMax := max(dfs(v.left), 0)
    rightMax := max(dfs(v.right), 0)
    maxPath := max(maxPath, v.val + leftMax + rightMax)
    return v.val + max(leftMax, rightMax)

Call dfs(root), then return maxPath. Time: O(n)O(n) (visit each node once). Space: O(h)O(h) for recursion stack where hh is tree height. On balanced trees, h=lognh = \log n. On skewed trees, h=nh = n.