Graph Theory37 sections · 1633 units
Open in Course

LeetCode 124 Binary Tree Maximum Path Sum - Algorithm

DFS with global max

Run DFS from root. For each node:

1.1. Compute extleftMax=max(extdfs(extleft),0) ext{leftMax} = max( ext{dfs}( ext{left}), 0).

2.2. Compute extrightMax=max(extdfs(extright),0) ext{rightMax} = max( ext{dfs}( ext{right}), 0).

3.3. Update extmaxPath=max(extmaxPath,v+extleftMax+extrightMax) ext{maxPath} = max( ext{maxPath}, v + ext{leftMax} + ext{rightMax}).

4.4. Return v+max(extleftMax,extrightMax)v + max( ext{leftMax}, ext{rightMax}) to parent.

After DFS, return extmaxPath ext{maxPath}. The global variable accumulates the best answer seen at any node.

This runs in O(n)O(n) time and uses O(n)O(n) space.