Maximum path sum from any node | Practice | GeeksforGeeks

Given a binary tree, the task is to find the maximum path sum. The path may start and end at any node in the tree.
Example 1:
Input:
     10
    /  \
   2   -25
  / \  /  \
 20 1  3  4
Output: 32
Explanation: Path in the given tree goes
like 10 , 2 , 20 which gives the max
sum as 32.

Example 2:
Input:
     10
   /    \
  2      5
          \
          -2
Output: 17
Explanation: Path in the given tree goes
like 2 , 10 , 5 which gives the max sum
as 17.
Your Task:
You don't need to take input or print anything. Your task is to complete the function findMaxSum() that takes root as input and returns max sum between any two nodes in the given Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
Constraints:
1 ≤ Number of nodes ≤ 103
1 ≤ |Data on node| ≤ 104
0
apurvkumarak3 weeks ago
C++ Solution  
struct Intpair{
    int first;
    int second;
    Intpair(){
        first=0;
        second=0;
    }
    Intpair(int a,int b){
        first=a;
        second=b;
    }
};
class Solution {
  public:
    //Function to return maximum path sum from any node in a tree.
    Intpair pathSum(Node * node,vector<Node*> & vec,std::unordered_map<Node*,Intpair> & mp,int & val){
        if(node != NULL){
            int leftSum=0;
            int rightSum=0;
            val=std::max(val,node->data);
            if(node->left != NULL){
                auto res1=pathSum(node->left,vec,mp,val);
                leftSum+=std::max(res1.first,std::max(res1.second,0));
            }
            if(node->right != NULL){
                auto res2=pathSum(node->right,vec,mp,val);
                rightSum+=std::max(res2.second,std::max(res2.first,0));
            }
            if(!mp.count(node)){
                mp[node]=Intpair(leftSum,rightSum);
                if(node->left != NULL || node->right != NULL){
                    vec.push_back(node);
                }
            }else{
                leftSum=std::max(mp[node].first,leftSum);
                rightSum=std::max(mp[node].second,rightSum);
                mp[node]=Intpair(leftSum,rightSum);
            }
            return Intpair(node->data+leftSum,node->data+rightSum);
        }
        return Intpair(INT_MIN,INT_MIN);
    }
    int findMaxSum(Node* root)
    {
        if(root == NULL){
            return INT_MIN;
        }
        if(root->left == NULL && root->right == NULL){
            return root->data;
        }
        int max_val=root->data;
        std::unordered_map<Node*,Intpair> mp;
        vector<Node *> vec;
        pathSum(root,vec,mp,max_val);
        int res=INT_MIN;
        for(int i=0;i<vec.size();i++){
            Node * temp= vec[i];
            int temp1=mp[temp].first+mp[temp].second+temp->data;
            res=std::max(res,temp1);
        }
        res=std::max(res,max_val);
        return res;   
    }

};
0
shvmsh203 weeks ago
Can somebody help me know why this code is giving wrong ans
int solve(Node *root, int &res){       if(root==NULL)           return 0;       int l = solve(root->left, res);       int r = solve(root->right, res);              int temp = max(root->data, ((root->data)+max(l, r)));       int ans = max(temp, (root->data+l+r));       res = max(res, ans);       return temp;   }   int findMaxSum(Node* root)   {       // Your code goes here       int res=INT_MIN;       return solve(root, res);       return res;   }
 
But this code pass all test cases
int solve(Node* root,int &res){       if(root == NULL)           return 0;       int l = solve(root->left,res);       int r = solve(root->right,res);              int temp = max(max(l,r)+root->data,root->data);       int ans = max(temp,l+r+root->data);       res = max(res,ans);       return temp;   }   int findMaxSum(Node* root)   {       int res=INT_MIN;       solve(root,res);       return res;   }
 
0
swastikp17113 weeks ago
simple Java and C++ Solution ( using Aditya Verma General Syntax )
 
Java solution
class Solution
{
    //Function to return maximum path sum from any node in a tree.
    int res=Integer.MIN_VALUE;
    int findMaxSumUtil(Node root){
        if(root==null){
            return 0;
        }
        
        int l=findMaxSumUtil(root.left);
        int r=findMaxSumUtil(root.right);
        
        int temp=Math.max((Math.max(l,r)+root.data),root.data);
        int ans=Math.max(temp,l+r+root.data);
        res=Math.max(res,ans);
        
        return temp;
    }
    int findMaxSum(Node root)
    {
        findMaxSumUtil(root);
        return res;
    }
}
 
C++ Solution 
class Solution {
  public:
    //Function to return maximum path sum from any node in a tree.
    int solve(Node* root,int &res){
        if(root == NULL)
            return 0;
        int l = solve(root->left,res);
        int r = solve(root->right,res);
        
        int temp = max(max(l,r)+root->data,root->data);
        int ans = max(temp,l+r+root->data);
        res = max(res,ans);
        return temp;
    }
    int findMaxSum(Node* root)
    {
        int res=INT_MIN;
        solve(root,res);
        return res;
    }
};
0
adarshgupta4011 month ago
Easy JAva Soln 
class Solution
{
    //Function to return maximum path sum from any node in a tree.
    int maxValue = Integer.MIN_VALUE;
    public int findMaxSum(Node root) {
        maxSumDown(root);
        return maxValue;
    }
    private int maxSumDown( Node root){ 
        if(root == null) return 0;
        int leftSum = Math.max(0, maxSumDown(root.left));
        int rightSum = Math.max(0, maxSumDown(root.right));
        maxValue = Math.max(maxValue, leftSum+rightSum+root.data );
        
        return root.data+ Math.max( leftSum, rightSum);    
    }
}

0
himanshu11042003singh1 month ago
class Solution { public:   //Function to return maximum path sum from any node in a tree.    int maxPath(Node* node,int &maxi){       if(node==NULL)return 0;       int left=max(0,maxPath(node->left,maxi));       int right=max(0,maxPath(node->right,maxi));       maxi=max(maxi,left+right+node->data);       return max(left,right)+node->data;   }   int findMaxSum(Node* root)   {       // Your code goes here        int maxi=INT_MIN;       maxPath(root,maxi);       return maxi;   }}; 
0
codecrackerp2 months ago
 int sum(Node*root,int &maxi){
       if(root==NULL){
           return 0;
       }
       int lsum=max(0,sum(root->left,maxi));
       int rsum=max(0,sum(root->right,maxi));
       maxi=max(maxi,root->data+lsum+rsum);
       return (root->data+max(lsum,rsum));
   }
   int findMaxSum(Node* root)
   {
        int maxi=INT_MIN;
        if(root==NULL)return 0;
        int ans=sum(root,maxi);
        return maxi;
   }
+3
abhijeet194032 months ago
A simple approach is to check for left subtree with node,right subtree with node, left and right subtree with node or just the node and compare the maximum of all four with a maxSum variable initially given INT_MIN value, Now to procede further we can recursively call only left subree with node , right subtree with node and node's maximum 
 
Code in C++
 
class Solution { public:   //Function to return maximum path sum from any node in a tree.   int maxSum = INT_MIN;   int findMax(Node * root)   {       if(root==NULL)       return 0;       int l = findMax(root->left); //left subtree       int r = findMax(root->right); // right subtree       int a = max(l+root->data,r+root->data);       int b = max(l+r+root->data,root->data);// to get the maximum of the four conditions        maxSum = max(maxSum,max(a,b)); // to check the maximum value found yet       return max(a,root->data); // to further procede with the tree   }   int findMaxSum(Node* root)   {             if(root==NULL)       return 0;       findMax(root); // calling findMax()       return maxSum; // returning the maximum value found in the tree   }};
 
If you liked the approach give a thumbs up.
0
baibhavrajputt2 months ago
Java solution
class Solution
{
    int maxi = Integer.MIN_VALUE;
    //Function to return maximum path sum from any node in a tree.
    int findMaxSum(Node node)
    {
        //your code goes here
        solution(node);
        return maxi;
    }
    int solution(Node root){
        
        if(root == null)
            return 0;
            
        int left = Math.max(0 , solution(root.left));
        int right = Math.max(0 , solution(root.right));
        
        maxi = Math.max(maxi , left + right + root.data);
        
        return root.data + Math.max(left , right);
    }
}
0
devendray21063 months ago
for ip -2 -10 -90 op is -2 but my code is producing op = 0 what is wrong with my code
 
   int solve(Node* root,int &res){
        if(root == NULL)
            return 0;
        int l = solve(root->left,res);
        int r = solve(root->right,res);
        
        int temp = max(max(l,r)+root->data,root->data);
        int ans = max(temp,l+r+root->data);
        res = max(res,ans);
        return temp;
    }
    int findMaxSum(Node* root)
    {
        int res;
        solve(root,res);
        return res;
    }
 
0
krishnarathi3413 months ago
0.0/1.1 time taken c++ solution
To solve using recursion we need subtrees to return the maximum sum they can return with linear connection of nodes, So, subtrees can   return max(root→data, root→data + max(ls,rs)); 
to its parent. (ls is the maxium sum left subtree can return and rs is for right subtree).
 
on the other hand maxPathSum may contain maximum of  root→data or  root→data + max(ls,rs) or root→data + ls + rs  where root can be root any root present in left or right subtree.
 
int findMax(Node *root,int &maxPathSum){
  if(root == NULL) return 0;
  int ls = findMax(root->left,maxPathSum);
  int rs = findMax(root->right,maxPathSum);
  int mp = max(root->data, root->data + max(ls,rs));
  maxPathSum = max(maxPathSum, max(mp, ls+rs+root->data));
  return mp;
}
  
    //Function to return maximum path sum from any node in a tree.
    int findMaxSum(Node* root)
    {
        // Your code goes here
        if(root == NULL) return 0;
        int maxPathSum = INT_MIN;
        int treeMax = findMax(root,maxPathSum);
        return max(maxPathSum,treeMax);
    }
Time complexity: O(N)
space complexity: O(H)
using idea of post order traversal
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.