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
See below diagram for another example.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
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 The idea is to keep trace of four paths and pick up the max one in the end. An important thing to note is, root of every subtree need to return maximum path sum such that at most one child of root is involved. This is needed for parent function call. In below code, this sum is stored in ‘max_single’ and returned by the recursive function.
// C/C++ program to find maximum path sum in Binary Tree
// A binary tree node
structNode* left, *right;
// A utility function to allocate a new node
structNode* newNode = newNode;
newNode->data = data;
newNode->left = newNode->right = NULL;
// This function returns overall maximum path sum in 'res'
// And returns max path sum going through root.
intfindMaxUtil(Node* root, int&res)
if(root == NULL)
// l and r store maximum path sum going through left and
// right child of root respectively
intl = findMaxUtil(root->left,res);
intr = findMaxUtil(root->right,res);
// Max path for parent call of root. This path must