Given a binary tree, write an efficient algorithm to find the maximum path sum between any two nodes in it. The path can start and end at any node in the tree and need not go through the root.

For example, the maximum sum path in the following binary tree is highlighted in green.


Binary Tree - Maximum Path Sum
Find maximum sum path between two leaves in a binary tree

We have discussed finding the maximum path sum in a binary tree that starts & ends at a leaf node in the above post. In the current problem, there is no such restriction on where the path can start or end.

A simple solution is to traverse the tree and, for every node, calculate the maximum sum path starting from it and passing through its left child and right child. Keep track of the maximum among all the maximum sum paths found and return it after all nodes are processed. The time complexity of this solution is O(n2).

We can reduce the time complexity to linear by traversing the tree in a bottom-up manner. Each node returns the maximum path sum “starting” at that node to its parent. To ensure that the maximum path sum “starts” at that node, at most, one child of the node should be involved.
The maximum path sum passing “through” a node is the maximum of:
The algorithm can be implemented as follows in C++, Java, and Python. Note that the maximum path sum is passed by reference to the function (instead of returning it), and its value is updated within the function.

C++

Download   Run Code

Output:

The maximum path sum is 15

Java

Download   Run Code

Output:

The maximum path sum is 15

Python

Download   Run Code

Output:

The maximum path sum is 15

Download   Run Code
Output:

The maximum path sum is 15

Download   Run Code
Output:

The maximum path sum is 15

Download   Run Code
Output:

The maximum path sum is 15

The time complexity of the above solution is O(n), where n is a number of nodes in the binary tree. The auxiliary space used by the program is O(h) for the call stack, where h is the height of the tree.
source