Find the maximum path sum between two leaves of a binary tree
Given a binary tree in which each node element contains a number. Find the maximum possible sum from one leaf node to another.
The maximum sum path may or may not go through root. For example, in the following binary tree, the maximum sum is 27(3 + 6 + 9 + 0 – 1 + 10). Expected time complexity is O(n). If one side of root is empty, then function should return minus infinite (INT_MIN in case of C/C++)
A simple solution is to traverse the tree and do following for every traversed node X.
- Find maximum sum from leaf to root in left subtree of X (we can use this post for this and next steps)
- Find maximum sum from leaf to root in right subtree of X.
- Add the above two calculated values and X->data and compare the sum with the maximum value obtained so far and update the maximum value.
- Return the maximum value.
The time complexity of above solution is O(n2)
We can find the maximum sum using single traversal of binary tree. The idea is to maintain two values in recursive calls
(Note: If the tree is right-most or left-most tree then first we have to adjust the tree such that both the right and left are not null. Left-most means if the right of super root of the tree is null and right-most tree means if left of super root of the tree is null.)
- Maximum root to leaf path sum for the subtree rooted under current node.
- The maximum path sum between leaves (desired output).
For every visited node X, we find the maximum root to leaf sum in left and right subtrees of X. We add the two values with X->data, and compare the sum with maximum path sum found so far.
Following is the implementation of the above O(n) solution.
Max pathSum of the given binary tree is 27
Time complexity: O(n) where n is the number of nodes
Auxiliary Space: O(1)