Search⌘ K
AI Features

Solution: Binary Tree Maximum Path Sum

Explore the solution to calculate the maximum sum of any path in a binary tree using depth-first search. Understand how to recursively evaluate node contributions, decide when to start a new path, and update the global maximum sum. This lesson helps you implement an efficient O(n) time and O(h) space algorithm by managing positive and negative node values effectively.

Statement

Given the root of a binary tree, return the maximum sum of any non-empty path.

A path in a binary tree is defined as follows:

  • A sequence of nodes in which each pair of adjacent nodes must have an edge connecting them.
    • A node can only be included in a path once at most.
    • Including the root in the path is not compulsory.

You can calculate the path sum by adding up all node values in the path. To solve this problem, calculate the maximum path sum given the root of a binary tree so that there won’t be any greater path than it in the tree.

Constraints:

  • 11\leq Number of nodes in the tree 500\leq500.
  • 1000
...