Home
Log in
DescriptionSubmissionsSolution
DescriptionSubmissionsSolution
Loading...

Log in to run or submit

root =

Codey

Practise coding problems, test your solutions and track your progress.

Explore

  • Problems
  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

© 2026 Codey. Personal learning project.

Solution
Updated: 2026-02-23

Idea

A max path either passes through a node using both sides, or continues upward using only one side.

Approach

DFS returns the best “gain” from a node to its parent: node.val + max(0, leftGain, rightGain). Update a global answer with a path that uses both sides: node.val + max(0,left) + max(0,right).

Why it works

Every maximum path has a highest node where the path turns (may include both children). Evaluating each node as that turn covers all paths.

Code
Loading...
Complexity
Time: O(n)
Space: O(h)
Solution
Updated: 2026-02-23

Idea

A max path either passes through a node using both sides, or continues upward using only one side.

Approach

DFS returns the best “gain” from a node to its parent: node.val + max(0, leftGain, rightGain). Update a global answer with a path that uses both sides: node.val + max(0,left) + max(0,right).

Why it works

Every maximum path has a highest node where the path turns (may include both children). Evaluating each node as that turn covers all paths.

Code
Loading...
Complexity
Time: O(n)
Space: O(h)