Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 124 Binary Tree Maximum Path Sum - Implementation

Handling negative values

Negative nodes complicate things. We might want to exclude a subtree entirely if its contribution is negative. Trick: when computing maxDownmaxDown, take max(0,childMaxDown)\max(0, childMaxDown). This lets us "cut off" negative subtrees. Base case: null node returns maxDown=0maxDown = 0, maxPath=maxPath = -\infty. Leaf returns (val,val)(val, val). Time: O(n)O(n) single post-order traversal. Space: O(h)O(h) for recursion stack where hh is tree height.

Time complexity: O(n)O(n).

Space complexity: O(h)O(h).