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

Practice this problem

Related Post:

Find the maximum sum path between two leaves in a binary tree

 
We have discussed finding the maximum path sum in a binary tree that starts and 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 would be to traverse the tree and, for every node, calculate the maximum sum path starting from it and passing through its left 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), where n is the total number of nodes in the binary tree.

 
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 following:

  1. Node’s value.
  2. Node’s value + maximum path sum “starting” from its left child.
  3. Node’s value + maximum path sum “starting” from its right child.
  4. Node’s value + maximum path sum “starting” from its left child + maximum path sum “starting” from its right child.

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

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