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:
Input:
Output: 42 Explanation: Max path sum is represented using green colour nodes in the above binary tree.
Input:
Output: 31 Explanation: Max path sum is represented using green colour nodes in the above binary tree.
Approach:
If the maximum sum path in a binary tree passes through the root, there are four possible cases to consider:
The path consists only the rootitself, without involving any children.
The path starts at the root and extends downward through its rightchild, possibly continuing to the bottom of the right subtree.
The path starts at the root and extends downward through its left child, possibly continuing the bottom of the left subtree.
The path includes the root and spans both the left and right children.
The idea is to keep track of all four paths for each subtree of the tree and pick up the max one in the end.
Implementation:
For each subtree, we want to find the maximum path sum that starts at its root and goes down through either its left or right child. To do this, we create a recursive function (lets say MPS(current root)) that calculates and returns the maximum path sum starting from the root and extending downward through one of its children.
Within the same function, we can also calculate the maximum path sum for the current subtree and compare it with the final answer. This is done by combining the MPS(current root -> left) and MPS(current root -> right) with the value of the current root.
Note that if the MPS() from the left or right child is negative, we simply ignore it while calculating the maximum path sum for the current subtree.
C++
//Driver Code Starts// C++ program to find maximum path sum in Binary Tree#include<iostream>usingnamespacestd;classNode{public:intdata;Node*left,*right;// Constructor to initialize a new nodeNode(intvalue){data=value;left=nullptr;right=nullptr;}};//Driver Code Ends// Returns the maximum path sum in the subtree with the current node as an endpoint. // Also updates 'res' with the maximum path sum.intmaxPathSumUtil(Node*root,int&res){// Base case: return 0 for a null nodeif(root==NULL)return0;// Calculate maximum path sums for left and right subtreesintl=max(0,maxPathSumUtil(root->left,res));intr=max(0,maxPathSumUtil(root->right,res));// Update 'res' with the maximum path sum passing through the current noderes=max(res,l+r+root->data);// Return the maximum path sum rooted at this nodereturnroot->data+max(l,r);}// Returns maximum path sum in tree with given rootintmaxPathSum(Node*root){intres=root->data;// Compute maximum path sum and store it in 'res'maxPathSumUtil(root,res);returnres;}//Driver Code Startsintmain(){// Representation of input binary tree:// 10// / \ // 2 10// / \ \ // 20 1 -25// / \ // 3 4Node*root=newNode(10);root->left=newNode(2);root->right=newNode(10);root->left->left=newNode(20);root->left->right=newNode(1);root->right->right=newNode(-25);root->right->right->left=newNode(3);root->right->right->right=newNode(4);cout<<maxPathSum(root);return0;}//Driver Code Ends
Java
//Driver Code Starts// Java program to find maximum path sum in Binary TreeclassNode{intdata;Nodeleft,right;// Constructor to initialize a new nodeNode(intvalue){data=value;left=null;right=null;}}//Driver Code EndsclassGfG{// Returns the maximum path sum in the subtree with the current node as an endpoint.// Also updates 'res' with the maximum path sum.staticintmaxPathSumUtil(Noderoot,int[]res){// Base case: return 0 for a null nodeif(root==null)return0;// Calculate maximum path sums for left and right subtreesintl=Math.max(0,maxPathSumUtil(root.left,res));intr=Math.max(0,maxPathSumUtil(root.right,res));// Update 'res' with the maximum path sum passing through the current noderes[0]=Math.max(res[0],l+r+root.data);// Return the maximum path sum rooted at this nodereturnroot.data+Math.max(l,r);}// Returns maximum path sum in tree with given rootstaticintmaxPathSum(Noderoot){int[]res={root.data};// Compute maximum path sum and store it in 'res'maxPathSumUtil(root,res);returnres[0];}//Driver Code Startspublicstaticvoidmain(String[]args){// Representation of input binary tree:// 10// / \// 2 10// / \ \// 20 1 -25// / \// 3 4Noderoot=newNode(10);root.left=newNode(2);root.right=newNode(10);root.left.left=newNode(20);root.left.right=newNode(1);root.right.right=newNode(-25);root.right.right.left=newNode(3);root.right.right.right=newNode(4);System.out.println(maxPathSum(root));}}//Driver Code Ends
Python
//DriverCodeStarts# Python program to find maximum path sum in Binary TreeclassNode:# Constructor to initialize a new nodedef__init__(self,value):self.data=valueself.left=Noneself.right=None//DriverCodeEnds# Returns the maximum path sum in the subtree with the current node as an endpoint.# Also updates 'res' with the maximum path sum.defmaxPathSumUtil(root,res):# Base case: return 0 for a null nodeifrootisNone:return0# Calculate maximum path sums for left and right subtreesl=max(0,maxPathSumUtil(root.left,res))r=max(0,maxPathSumUtil(root.right,res))# Update 'res' with the maximum path sum passing through the current noderes[0]=max(res[0],l+r+root.data)# Return the maximum path sum rooted at this nodereturnroot.data+max(l,r)# Returns maximum path sum in tree with given rootdefmaxPathSum(root):res=[root.data]# Compute maximum path sum and store it in 'res'maxPathSumUtil(root,res)returnres[0]//DriverCodeStartsif__name__=="__main__":# Representation of input binary tree:# 10# / \# 2 10# / \ \# 20 1 -25# / \# 3 4root=Node(10)root.left=Node(2)root.right=Node(10)root.left.left=Node(20)root.left.right=Node(1)root.right.right=Node(-25)root.right.right.left=Node(3)root.right.right.right=Node(4)print(maxPathSum(root))//DriverCodeEnds
C#
//Driver Code Starts// C# program to find maximum path sum in Binary TreeusingSystem;classNode{publicintdata;publicNodeleft,right;// Constructor to initialize a new nodepublicNode(intvalue){data=value;left=null;right=null;}}classGfG{//Driver Code Ends// Returns the maximum path sum in the subtree with the current node as an endpoint.// Also updates 'res' with the maximum path sum.staticintmaxPathSumUtil(Noderoot,refintres){// Base case: return 0 for a null nodeif(root==null)return0;// Calculate maximum path sums for left and right subtreesintl=Math.Max(0,maxPathSumUtil(root.left,refres));intr=Math.Max(0,maxPathSumUtil(root.right,refres));// Update 'res' with the maximum path sum passing through the current noderes=Math.Max(res,l+r+root.data);// Return the maximum path sum rooted at this nodereturnroot.data+Math.Max(l,r);}// Returns maximum path sum in tree with given rootstaticintmaxPathSum(Noderoot){intres=root.data;// Compute maximum path sum and store it in 'res'maxPathSumUtil(root,refres);returnres;}//Driver Code StartsstaticvoidMain(string[]args){// Representation of input binary tree:// 10// / \// 2 10// / \ \// 20 1 -25// / \// 3 4Noderoot=newNode(10);root.left=newNode(2);root.right=newNode(10);root.left.left=newNode(20);root.left.right=newNode(1);root.right.right=newNode(-25);root.right.right.left=newNode(3);root.right.right.right=newNode(4);Console.WriteLine(maxPathSum(root));}}//Driver Code Ends
JavaScript
//Driver Code Starts// JavaScript program to find maximum path sum in Binary TreeclassNode{constructor(value){// Constructor to initialize a new nodethis.data=value;this.left=null;this.right=null;}}//Driver Code Ends// Returns the maximum path sum in the subtree with the current node as an endpoint.// Also updates 'res' with the maximum path sum.functionmaxPathSumUtil(root,res){// Base case: return 0 for a null nodeif(root===null)return0;// Calculate maximum path sums for left and right subtreesconstl=Math.max(0,maxPathSumUtil(root.left,res));constr=Math.max(0,maxPathSumUtil(root.right,res));// Update 'res' with the maximum path sum passing through the current noderes.value=Math.max(res.value,l+r+root.data);// Return the maximum path sum rooted at this nodereturnroot.data+Math.max(l,r);}// Returns maximum path sum in tree with given rootfunctionmaxPathSum(root){constres={value:root.data};// Compute maximum path sum and store it in 'res'maxPathSumUtil(root,res);returnres.value;}//Driver Code Starts// Driver Code// Representation of input binary tree:// 10// / \// 2 10// / \ \// 20 1 -25// / \// 3 4constroot=newNode(10);root.left=newNode(2);root.right=newNode(10);root.left.left=newNode(20);root.left.right=newNode(1);root.right.right=newNode(-25);root.right.right.left=newNode(3);root.right.right.right=newNode(4);console.log(maxPathSum(root));//Driver Code Ends
Output
42
Time Complexity: O(n), where n is the number of nodes in the Binary Tree. Auxiliary Space: O(h), where h is the height of the tree.