Binary Tree Maximum Path Sum

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

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:

“A sequence of nodes such that each pair of adjacent nodes must have an edge connecting them. A node can only be included in a path at most once. Moreover, including the root in the path is not compulsory.”

We can calculate the path sum by adding up all nodes’ values in the path. To solve this problem, we’ll 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.

Example

For the following tree, the maximum path sum is:

19>17>519 -> 17 -> 5, and the total sum = 4141.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.