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) ;
}
---------------------------------------------------------------------------------
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
Post a Comment