#124

Binary Tree Maximum Path Sum

Hard Gain function with global best

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

A path is any sequence of connected nodes, used at most once each, not necessarily through the root. Return the maximum sum of node values on any path.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the largest sum along any path.

Why this works: each node returns its best downward path (one side only). A path that bends at the node uses both sides; update the global best with it.

Example: -10 (9, 20 (15, 7))

at 20: bend 15 + 20 + 7 = 42 (best)return 20 + 15 = 35 upat -10: 9 - 10 + 35 = 34 < 42

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Returning the bent path (both children) to the parent — a parent can only extend a path down one side.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(h).
Topic: Binary Trees
🎬 Episodes 53–60: video coming soon