Maximum Path Sum in a Binary Tree

PROBLEM :

Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree.

Example:

Input: Root of below tree
       1
      / \
     2   3
Output: 6

See below diagram for another example.
1+2+3


   
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*
For each node there can be four ways that the max path goes through the node:
1. Node only
2. Max path through Left Child + Node
3. Max path through Right Child + Node
4. Max path through Left Child + Node + Max path through Right Child */


/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;---------------------------------------------*/

int max_of(int ,int ) ;

int max_sum_path(tree *root,int *maxSum)
{
if(root==NULL)
return 0 ;

int LSum,RSum,max1,max2 ;

LSum=max_sum_path(root->left,&(*maxSum)) ;
RSum=max_sum_path(root->right,&(*maxSum)) ;

max1=max_of(max_of(LSum,RSum)+root->info,root->info) ;

max2=max_of(LSum+RSum+root->info,max1) ;

(*maxSum)=max_of((*maxSum),max2) ;

return max1 ;
}

int max_of(int first,int second)
{
return((first>second)?first:second) ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )