Given a binary tree, write an efficient algorithm to find the maximum sum of a path between any two leaves in it. Assume that the binary tree is not skewed and contains at-least two nodes.

For example, the maximum sum path in the following binary tree is 22:

 
Maximum Sum Path

Practice this problem

A simple solution would be to calculate the maximum sum node-to-leaf path from the left and right child for every node in the tree. The maximum sum path between two leaves that passes through a node has a value equal to the maximum sum node-to-leaf path of its left and right child plus the node’s value. Finally, consider the maximum value among all maximum sum paths found for every node in the tree.

The time complexity of this solution is O(n2) as there are n nodes in the tree, and for every node, we are calculating the maximum sum node-to-leaf path of its left and right subtree that takes O(n) time.

 
We can solve this problem in linear time by traversing the tree in a bottom-up manner. Instead of calculating the maximum sum node-to-leaf path of the left and right child for every node in the tree, calculate the maximum sum path between two leaves that passes through a node in constant time. The idea is to start from the bottom of the tree and return the maximum sum node-to-leaf path for each node to its parent.

The algorithm can be implemented as follows in C++, Java, and Python. Here, we pass the maximum sum path by reference to the function (instead of returning it) and update its value within the function itself using the return value of the left and right subtrees.

C++


Download  Run Code

Output:

22

Java


Download  Run Code

Output:

22

Python


Download  Run Code

Output:

22

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