Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Maximum Path Sum in a Binary Tree
Next article icon

Maximum Path Sum in a Binary Tree

Last Updated : 03 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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: 

tree-2


Output: 42
Explanation: Max path sum is represented using green colour nodes in the above binary tree.

Input:

Tree-Image

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:

  1. The path consists only the root itself, without involving any children.
  2. The path starts at the root and extends downward through its right child, possibly continuing to the bottom of the right subtree.
  3. The path starts at the root and extends downward through its left child, possibly continuing the bottom of the left subtree.
  4. 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> using namespace std;  class Node { public:     int data;     Node *left, *right;      // Constructor to initialize a new node     Node(int value) {         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. int maxPathSumUtil(Node* root, int& res) {        // Base case: return 0 for a null node     if (root == NULL)         return 0;      // Calculate maximum path sums for left and right subtrees     int l = max(0, maxPathSumUtil(root->left, res));     int r = max(0, maxPathSumUtil(root->right, res));      // Update 'res' with the maximum path sum passing through the current node     res = max(res, l + r + root->data);      // Return the maximum path sum rooted at this node     return root->data + max(l, r); }  // Returns maximum path sum in tree with given root int maxPathSum(Node* root) {     int res = root->data; 	   	// Compute maximum path sum and store it in 'res'     maxPathSumUtil(root, res);        return res; }   //Driver Code Starts int main() {   	 	// Representation of input binary tree:     //            10     //           /  \     //          2    10     //         / \     \       //        20  1    -25   	//                 /  \   	//				  3	   4     Node* root = new Node(10);     root->left = new Node(2);     root->right = new Node(10);     root->left->left = new Node(20);     root->left->right = new Node(1);     root->right->right = new Node(-25);     root->right->right->left = new Node(3);     root->right->right->right = new Node(4);      cout << maxPathSum(root);     return 0; } //Driver Code Ends 
Java
//Driver Code Starts // Java program to find maximum path sum in Binary Tree class Node {     int data;     Node left, right;      // Constructor to initialize a new node     Node(int value) {         data = value;         left = null;         right = null;     } } //Driver Code Ends   class GfG {      // Returns the maximum path sum in the subtree with the current node as an endpoint.     // Also updates 'res' with the maximum path sum.     static int maxPathSumUtil(Node root, int[] res) {         // Base case: return 0 for a null node         if (root == null) return 0;          // Calculate maximum path sums for left and right subtrees         int l = Math.max(0, maxPathSumUtil(root.left, res));         int r = Math.max(0, maxPathSumUtil(root.right, res));          // Update 'res' with the maximum path sum passing through the current node         res[0] = Math.max(res[0], l + r + root.data);          // Return the maximum path sum rooted at this node         return root.data + Math.max(l, r);     }      // Returns maximum path sum in tree with given root     static int maxPathSum(Node root) {         int[] res = {root.data};          // Compute maximum path sum and store it in 'res'         maxPathSumUtil(root, res);          return res[0];     }   //Driver Code Starts     public static void main(String[] args) {         // Representation of input binary tree:         //            10         //           /  \         //          2    10         //         / \     \         //        20  1    -25         //                 /  \         //                3    4         Node root = new Node(10);         root.left = new Node(2);         root.right = new Node(10);         root.left.left = new Node(20);         root.left.right = new Node(1);         root.right.right = new Node(-25);         root.right.right.left = new Node(3);         root.right.right.right = new Node(4);          System.out.println(maxPathSum(root));     } }  //Driver Code Ends 
Python
//Driver Code Starts # Python program to find maximum path sum in Binary Tree  class Node:     # Constructor to initialize a new node     def __init__(self, value):         self.data = value         self.left = None         self.right = None //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. def maxPathSumUtil(root, res):        # Base case: return 0 for a null node     if root is None:         return 0      # Calculate maximum path sums for left and right subtrees     l = max(0, maxPathSumUtil(root.left, res))     r = max(0, maxPathSumUtil(root.right, res))      # Update 'res' with the maximum path sum passing through the current node     res[0] = max(res[0], l + r + root.data)      # Return the maximum path sum rooted at this node     return root.data + max(l, r)  # Returns maximum path sum in tree with given root def maxPathSum(root):     res = [root.data]      # Compute maximum path sum and store it in 'res'     maxPathSumUtil(root, res)      return res[0]   //Driver Code Starts if __name__ == "__main__":     # Representation of input binary tree:     #            10     #           /  \     #          2    10     #         / \     \     #        20  1    -25     #                 /  \     #                3    4     root = 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))  //Driver Code Ends 
C#
//Driver Code Starts // C# program to find maximum path sum in Binary Tree using System;  class Node {     public int data;     public Node left, right;      // Constructor to initialize a new node     public Node(int value) {         data = value;         left = null;         right = null;     } }  class GfG { //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.     static int maxPathSumUtil(Node root, ref int res) {                // Base case: return 0 for a null node         if (root == null)             return 0;          // Calculate maximum path sums for left and right subtrees         int l = Math.Max(0, maxPathSumUtil(root.left, ref res));         int r = Math.Max(0, maxPathSumUtil(root.right, ref res));          // Update 'res' with the maximum path sum passing through the current node         res = Math.Max(res, l + r + root.data);          // Return the maximum path sum rooted at this node         return root.data + Math.Max(l, r);     }      // Returns maximum path sum in tree with given root     static int maxPathSum(Node root) {         int res = root.data;          // Compute maximum path sum and store it in 'res'         maxPathSumUtil(root, ref res);          return res;     }   //Driver Code Starts     static void Main(string[] args) {         // Representation of input binary tree:         //            10         //           /  \         //          2    10         //         / \     \         //        20  1    -25         //                 /  \         //                3    4         Node root = new Node(10);         root.left = new Node(2);         root.right = new Node(10);         root.left.left = new Node(20);         root.left.right = new Node(1);         root.right.right = new Node(-25);         root.right.right.left = new Node(3);         root.right.right.right = new Node(4);          Console.WriteLine(maxPathSum(root));     } }  //Driver Code Ends 
JavaScript
//Driver Code Starts // JavaScript program to find maximum path sum in Binary Tree  class Node {     constructor(value) {         // Constructor to initialize a new node         this.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. function maxPathSumUtil(root, res) {      // Base case: return 0 for a null node     if (root === null) return 0;      // Calculate maximum path sums for left and right subtrees     const l = Math.max(0, maxPathSumUtil(root.left, res));     const r = Math.max(0, maxPathSumUtil(root.right, res));      // Update 'res' with the maximum path sum passing through the current node     res.value = Math.max(res.value, l + r + root.data);      // Return the maximum path sum rooted at this node     return root.data + Math.max(l, r); }  // Returns maximum path sum in tree with given root function maxPathSum(root) {     const res = { value: root.data };      // Compute maximum path sum and store it in 'res'     maxPathSumUtil(root, res);      return res.value; }   //Driver Code Starts // Driver Code // Representation of input binary tree: //            10 //           /  \ //          2    10 //         / \     \ //        20  1    -25 //                 /  \ //                3    4 const root = new Node(10); root.left = new Node(2); root.right = new Node(10); root.left.left = new Node(20); root.left.right = new Node(1); root.right.right = new Node(-25); root.right.right.left = new Node(3); root.right.right.right = new Node(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.


Next Article
Maximum Path Sum in a Binary Tree

K

kartik
Improve
Article Tags :
  • Tree
  • DSA
Practice Tags :
  • Tree

Similar Reads

    Maximum Path sum in a N-ary Tree
    Given an undirected tree with n nodes numbered from 1 to n and an array arr[] where arr[i] denotes the value assigned to (i+1)th node. The connections between the nodes are provided in a 2-dimensional array edges[][]. The task is to find the maximum path sum between any two nodes. (Both the nodes ca
    7 min read
    Maximum spiral sum in Binary Tree
    Given a binary tree containing n nodes. The task is to find the maximum sum obtained when the tree is spirally traversed. In spiral traversal one by one all levels are being traversed with the root level traversed from right to left, then the next level from left to right, then further next level fr
    9 min read
    Maximum parent children sum in Binary tree
    Given a Binary Tree, find the maximum sum in a binary tree by adding the parent with its children. Exactly three Node needs to be added. If the tree does not have a node with both of its children as not NULL, return 0. We simply traverse the tree and find the Node that has the maximum sum. We need t
    5 min read
    Maximum product of any path in given Binary Tree
    Given a binary tree of N nodes, the task is to find the maximum product of the elements of any path in the binary tree. Note: A path starts from the root and ends at any leaf in the tree. Examples: Input: 4 / \ 2 8 / \ / \2 1 3 4 Output: 128Explanation: Path in the given tree goes like {4, 8, 4} whi
    5 min read
    Find the maximum sum leaf to root path in a Binary Tree
    Given a Binary Tree, the task is to find the maximum sum path from a leaf to a root.Example : Input: Output: 60Explanantion: There are three leaf to root paths 20->30->10, 5->30->10 and 15->10. The sums of these three paths are 60, 45 and 25 respectively. The maximum of them is 60 and
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences