Find the maximum sum leaf to root path in a Binary Tree
Last Updated : 03 Oct, 2024
Given a Binary Tree, the task is to find the maximum sum path from a leaf to a root.
Example :
Input:

Output: 60
Explanantion: 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 the path for maximum is 20->30->10.
[Naive Approach] By Checking Every Path – O(n * h) Time and O(n) Space
The idea is to check of all possible path from root to leaf recursively. So we check for every path that is from root to every leaf and take the sum which path has the maximum sum.
Follow the steps below to solve the problem:
- Traverse the binary tree form root to every node and maintain a parent map which contains the parent of a node.
- While traversing, if the current node don’t has left or right child, then the node is a leaf node.
- When we encounter a leaf node, call a separate function which calculates the sum from that leaf to root.
- The function calculates the sum by using parent map by recursively calling the function with parent node until we reach root.
- Maintain a variable which keeps and updates the maximum sum.
Below is the implementation of the above approach:
C++ // CPP program to find maximum sum leaf to root // path in Binary Tree by checking every path #include <bits/stdc++.h> using namespace std; class Node { public: int data; Node* left; Node* right; Node(int x) { data = x; left = right = nullptr; } }; // Helper function to calculate the sum // from a leaf node to the root int getSumOfPath(Node* root, unordered_map<Node*, Node*> &parent) { // If the current node has no parent, // return its data (it's the root) if (parent.find(root) == parent.end()) return root->data; // Recursively sum the current node data // with its parent's path sum return root->data + getSumOfPath(parent[root], parent); } // Function to calculate the maximum leaf-to-root path sum void sumCal(Node* root, int &maxx, unordered_map<Node*, Node*> &parent) { // Check if the current node is a leaf node if (root->left == nullptr && root->right == nullptr) { // Update the maximum sum if the // current path's sum is greater maxx = max(maxx, getSumOfPath(root, parent)); return; } // If the left child exists, set the // current node as its parent and recurse if (root->left) { parent[root->left] = root; sumCal(root->left, maxx, parent); } // If the right child exists, set the // current node as its parent and recurse if (root->right) { parent[root->right] = root; sumCal(root->right, maxx, parent); } } // Function to return the maximum leaf- // to-root path sum in the binary tree int maxPathSum(Node* root) { // To store each node's parent for path calculation unordered_map<Node*, Node*> parent; // Variable to store the maximum sum int maxx = 0; // Recursively calculate the sum for all paths sumCal(root, maxx, parent); // Return the maximum path sum found return maxx; } int main() { // Constructing tree given // 10 // / \ // -2 7 // / \ // 8 -4 Node *root = new Node(10); root->left = new Node(-2); root->right = new Node(7); root->left->left = new Node(8); root->left->right = new Node(-4); int sum = maxPathSum(root); cout << sum << endl; return 0; }
Java // Java program to find maximum sum leaf to root // path in Binary Tree by checking every path import java.util.HashMap; class Node { int data; Node left, right; Node(int x) { data = x; left = right = null; } } class GfG { // Helper function to calculate the sum // from a leaf node to the root static int getSumOfPath(Node root, HashMap<Node, Node> parent) { // If the current node has no parent, // return its data (it's the root) if (!parent.containsKey(root)) return root.data; // Recursively sum the current node data // with its parent's path sum return root.data + getSumOfPath(parent.get(root), parent); } // Function to calculate the maximum leaf-to-root path sum static void sumCal(Node root, int[] maxx, HashMap<Node, Node> parent) { // Check if the current node is a leaf node if (root.left == null && root.right == null) { // Update the maximum sum if the // current path's sum is greater maxx[0] = Math.max(maxx[0], getSumOfPath(root, parent)); return; } // If the left child exists, set the // current node as its parent and recurse if (root.left != null) { parent.put(root.left, root); sumCal(root.left, maxx, parent); } // If the right child exists, set the // current node as its parent and recurse if (root.right != null) { parent.put(root.right, root); sumCal(root.right, maxx, parent); } } // Function to return the maximum leaf-to-root // path sum in the binary tree static int maxPathSum(Node root) { // To store each node's parent for path calculation HashMap<Node, Node> parent = new HashMap<>(); // Variable to store the maximum sum int[] maxx = {0}; // Recursively calculate the sum for all paths sumCal(root, maxx, parent); // Return the maximum path sum found return maxx[0]; } public static void main(String[] args) { // Constructing tree given // 10 // / \ // -2 7 // / \ // 8 -4 Node root = new Node(10); root.left = new Node(-2); root.right = new Node(7); root.left.left = new Node(8); root.left.right = new Node(-4); int sum = maxPathSum(root); System.out.println(sum); } }
Python # Python program to find maximum sum leaf to root # path in Binary Tree by checking every path class Node: def __init__(self, x): self.data = x self.left = None self.right = None # Helper function to calculate the sum # from a leaf node to the root def get_sum_of_path(root, parent): # If the current node has no parent, # return its data (it's the root) if root not in parent: return root.data # Recursively sum the current node data # with its parent's path sum return root.data + get_sum_of_path(parent[root], parent) # Function to calculate the maximum leaf-to-root path sum def sum_cal(root, maxx, parent): # Check if the current node is a leaf node if root.left is None and root.right is None: # Update the maximum sum if the # current path's sum is greater maxx[0] = max(maxx[0], get_sum_of_path(root, parent)) return # If the left child exists, set the # current node as its parent and recurse if root.left: parent[root.left] = root sum_cal(root.left, maxx, parent) # If the right child exists, set the # current node as its parent and recurse if root.right: parent[root.right] = root sum_cal(root.right, maxx, parent) # Function to return the maximum leaf-to-root path # sum in the binary tree def max_path_sum(root): # To store each node's parent for # path calculation parent = {} # Variable to store the maximum sum maxx = [0] # Recursively calculate the sum for all paths sum_cal(root, maxx, parent) # Return the maximum path sum found return maxx[0] if __name__ == "__main__": # Constructing tree given # 10 # / \ # -2 7 # / \ # 8 -4 root = Node(10) root.left = Node(-2) root.right = Node(7) root.left.left = Node(8) root.left.right = Node(-4) sum_result = max_path_sum(root) print(sum_result)
C# // C# program to find maximum sum leaf to root // path in Binary Tree by checking every path using System; using System.Collections.Generic; class Node { public int data; public Node left, right; public Node(int x) { data = x; left = right = null; } } class GfG { // Helper function to calculate the sum // from a leaf node to the root static int getSumOfPath(Node root, Dictionary<Node, Node> parent) { // If the current node has no parent, // return its data (it's the root) if (!parent.ContainsKey(root)) return root.data; // Recursively sum the current node data // with its parent's path sum return root.data + getSumOfPath(parent[root], parent); } // Function to calculate the maximum leaf-to-root path sum static void sumCal(Node root, ref int maxx, Dictionary<Node, Node> parent) { // Check if the current node is a leaf node if (root.left == null && root.right == null) { // Update the maximum sum if the // current path's sum is greater maxx = Math.Max(maxx, getSumOfPath(root, parent)); return; } // If the left child exists, set the // current node as its parent and recurse if (root.left != null) { parent[root.left] = root; sumCal(root.left, ref maxx, parent); } // If the right child exists, set the // current node as its parent and recurse if (root.right != null) { parent[root.right] = root; sumCal(root.right, ref maxx, parent); } } // Function to return the maximum leaf-to-root // path sum in the binary tree static int maxPathSum(Node root) { // To store each node's parent for path calculation Dictionary<Node, Node> parent = new Dictionary<Node, Node>(); // Variable to store the maximum sum int maxx = 0; // Recursively calculate the sum for all paths sumCal(root, ref maxx, parent); // Return the maximum path sum found return maxx; } static void Main(string[] args) { // Constructing tree given // 10 // / \ // -2 7 // / \ // 8 -4 Node root = new Node(10); root.left = new Node(-2); root.right = new Node(7); root.left.left = new Node(8); root.left.right = new Node(-4); int sum = maxPathSum(root); Console.WriteLine(sum); } }
JavaScript // JavaScript program to find maximum sum leaf to root // path in Binary Tree by checking every path class Node { constructor(x) { this.data = x; this.left = this.right = null; } } // Helper function to calculate the sum // from a leaf node to the root function getSumOfPath(root, parent) { // If the current node has no parent, // return its data (it's the root) if (!parent.has(root)) return root.data; // Recursively sum the current node data // with its parent's path sum return root.data + getSumOfPath(parent.get(root), parent); } // Function to calculate the maximum leaf-to-root path sum function sumCal(root, maxx, parent) { // Check if the current node is a leaf node if (root.left === null && root.right === null) { // Update the maximum sum if the // current path's sum is greater maxx[0] = Math.max(maxx[0], getSumOfPath(root, parent)); return; } // If the left child exists, set the // current node as its parent and recurse if (root.left !== null) { parent.set(root.left, root); sumCal(root.left, maxx, parent); } // If the right child exists, set the // current node as its parent and recurse if (root.right !== null) { parent.set(root.right, root); sumCal(root.right, maxx, parent); } } // Function to return the maximum leaf-to-root path // sum in the binary tree function maxPathSum(root) { // To store each node's parent for path calculation let parent = new Map(); // Variable to store the maximum sum let maxx = [0]; // Recursively calculate the sum for all paths sumCal(root, maxx, parent); // Return the maximum path sum found return maxx[0]; } // Constructing tree given // 10 // / \ // -2 7 // / \ // 8 -4 let root = new Node(10); root.left = new Node(-2); root.right = new Node(7); root.left.left = new Node(8); root.left.right = new Node(-4); let sum = maxPathSum(root); console.log(sum);
Time Complexity: O(n * h) Where n is number of nodes in tree and h is height of tree.
Auxiliary Space: O(n)
[Expected Approach] By Keeping Track of Maximum Sum – O(n) Time and O(n) Space
The idea is to keep track of current sum and maximum sum while traversing the tree and update maximum sum if at leaf node current sum is greater them maximum sum.
Follow the steps below to solve the problem:
- If the node is the root, return its data.
- If the node is a leaf, Check where current sum is greater than maximum sum, then update maximum sum.
- For non-leaf nodes, update current sum and make recursive call on both left and right child.
Below is the implementation of the above approach:
C++ // CPP program to find maximum sum leaf to root // path in Binary Tree #include <bits/stdc++.h> using namespace std; class Node { public: int data; Node* left; Node* right; Node(int x) { data = x; left = right = nullptr; } }; // Helper function to find the leaf node that contributes // to the maximum sum and returns the maximum sum from the // root to that leaf void findMaxSum(Node* root, int currSum, int& mxSum) { if (root == nullptr) return; // Add the current node's data to the path sum currSum += root->data; // Check if this node is a leaf node if (root->left == nullptr && root->right == nullptr) { // Update the maximum sum and target // leaf if a higher sum is found if (currSum > mxSum) { mxSum = currSum; } } // Recursively check for the maximum sum // in the left and right subtrees findMaxSum(root->left, currSum, mxSum); findMaxSum(root->right, currSum, mxSum); } // Function to return the maximum sum // path from root to leaf int maxPathSum(Node* root) { // empty tree has sum 0 if (root == nullptr) return 0; // Initialize max sum as the smallest possible integer int mxSum = INT_MIN; // Find the target leaf and maximum sum findMaxSum(root, 0, mxSum); // Return the maximum sum found return mxSum; } int main() { // Constructing tree: // 10 // / \ // -2 7 // / \ // 8 -4 Node *root = new Node(10); root->left = new Node(-2); root->right = new Node(7); root->left->left = new Node(8); root->left->right = new Node(-4); int sum = maxPathSum(root); cout << sum << endl; return 0; }
C // C program to find maximum sum leaf to // root path in Binary Tree #include <stdio.h> #include <stdlib.h> #include <limits.h> struct Node { int data; struct Node* left; struct Node* right; }; // Helper function to find the leaf node that contributes // to the maximum sum and returns the maximum sum from the // root to that leaf void findMaxSum(struct Node* root, int currSum, int* mxSum) { if (root == NULL) return; // Add the current node's data to the path sum currSum += root->data; // Check if this node is a leaf node if (root->left == NULL && root->right == NULL) { // Update the maximum sum if a higher sum is found if (currSum > *mxSum) { *mxSum = currSum; } } // Recursively check for the maximum // sum in the left and right subtrees findMaxSum(root->left, currSum, mxSum); findMaxSum(root->right, currSum, mxSum); } // Function to return the maximum sum path from root to leaf int maxPathSum(struct Node* root) { // Empty tree has sum 0 if (root == NULL) return 0; // Initialize max sum as the smallest possible integer int mxSum = INT_MIN; // Find the target leaf and maximum sum findMaxSum(root, 0, &mxSum); // Return the maximum sum found return mxSum; } struct Node* createNode(int data) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = data; newNode->left = newNode->right = NULL; return newNode; } int main() { // Constructing tree: // 10 // / \ // -2 7 // / \ // 8 -4 struct Node* root = createNode(10); root->left = createNode(-2); root->right = createNode(7); root->left->left = createNode(8); root->left->right = createNode(-4); int sum = maxPathSum(root); printf("%d\n", sum); return 0; }
Java // Java program to find maximum sum leaf to // root path in Binary Tree class Node { int data; Node left, right; Node(int x) { data = x; left = right = null; } } class GfG { // Helper function to find the leaf node that contributes // to the maximum sum and returns the maximum sum from the // root to that leaf static void findMaxSum(Node root, int currSum, int[] mxSum) { if (root == null) return; // Add the current node's data to the path sum currSum += root.data; // Check if this node is a leaf node if (root.left == null && root.right == null) { // Update the maximum sum if a higher sum is found if (currSum > mxSum[0]) { mxSum[0] = currSum; } } // Recursively check for the maximum sum // in the left and right subtrees findMaxSum(root.left, currSum, mxSum); findMaxSum(root.right, currSum, mxSum); } // Function to return the maximum sum path from root to leaf static int maxPathSum(Node root) { // Empty tree has sum 0 if (root == null) return 0; // Initialize max sum as the smallest possible integer int[] mxSum = { Integer.MIN_VALUE }; // Find the target leaf and maximum sum findMaxSum(root, 0, mxSum); // Return the maximum sum found return mxSum[0]; } public static void main(String[] args) { // Constructing tree: // 10 // / \ // -2 7 // / \ // 8 -4 Node root = new Node(10); root.left = new Node(-2); root.right = new Node(7); root.left.left = new Node(8); root.left.right = new Node(-4); int sum = maxPathSum(root); System.out.println(sum); } }
Python # Python program to find maximum sum leaf # to root path in Binary Tree class Node: def __init__(self, x): self.data = x self.left = None self.right = None # Helper function to find the leaf node that contributes # to the maximum sum and returns the maximum sum from the # root to that leaf def findMaxSum(root, currSum, mxSum): if root is None: return # Add the current node's data to the path sum currSum += root.data # Check if this node is a leaf node if root.left is None and root.right is None: # Update the maximum sum if a higher sum is found if currSum > mxSum[0]: mxSum[0] = currSum # Recursively check for the maximum sum # in the left and right subtrees findMaxSum(root.left, currSum, mxSum) findMaxSum(root.right, currSum, mxSum) # Function to return the maximum sum path # from root to leaf def maxPathSum(root): # Empty tree has sum 0 if root is None: return 0 # Initialize max sum as the smallest possible integer mxSum = [-float('inf')] # Find the target leaf and maximum sum findMaxSum(root, 0, mxSum) # Return the maximum sum found return mxSum[0] if __name__ == "__main__": # Constructing tree: # 10 # / \ # -2 7 # / \ # 8 -4 root = Node(10) root.left = Node(-2) root.right = Node(7) root.left.left = Node(8) root.left.right = Node(-4) sum = maxPathSum(root) print(sum)
C# // C# program to find maximum sum leaf // to root path in Binary Tree using System; class Node { public int data; public Node left, right; public Node(int x) { data = x; left = right = null; } } class GfG { // Helper function to find the leaf node that contributes // to the maximum sum and returns the maximum sum from the // root to that leaf static void findMaxSum(Node root, int currSum, ref int mxSum) { if (root == null) return; // Add the current node's data to the path sum currSum += root.data; // Check if this node is a leaf node if (root.left == null && root.right == null) { // Update the maximum sum if a higher sum is found if (currSum > mxSum) { mxSum = currSum; } } // Recursively check for the maximum // sum in the left and right subtrees findMaxSum(root.left, currSum, ref mxSum); findMaxSum(root.right, currSum, ref mxSum); } // Function to return the maximum sum path from root to leaf static int maxPathSum(Node root) { // Empty tree has sum 0 if (root == null) return 0; // Initialize max sum as the smallest possible integer int mxSum = int.MinValue; // Find the target leaf and maximum sum findMaxSum(root, 0, ref mxSum); // Return the maximum sum found return mxSum; } static void Main() { // Constructing tree: // 10 // / \ // -2 7 // / \ // 8 -4 Node root = new Node(10); root.left = new Node(-2); root.right = new Node(7); root.left.left = new Node(8); root.left.right = new Node(-4); int sum = maxPathSum(root); Console.WriteLine(sum); } }
JavaScript // JavaScript program to find maximum // sum leaf to root path in Binary Tree class Node { constructor(x) { this.data = x; this.left = null; this.right = null; } } // Helper function to find the leaf node that contributes // to the maximum sum and returns the maximum sum from the // root to that leaf function findMaxSum(root, currSum, mxSum) { if (root === null) return; // Add the current node's data to the path sum currSum += root.data; // Check if this node is a leaf node if (root.left === null && root.right === null) { // Update the maximum sum if a higher sum is found if (currSum > mxSum[0]) { mxSum[0] = currSum; } } // Recursively check for the maximum sum // in the left and right subtrees findMaxSum(root.left, currSum, mxSum); findMaxSum(root.right, currSum, mxSum); } // Function to return the maximum sum path from // root to leaf function maxPathSum(root) { // Empty tree has sum 0 if (root === null) return 0; // Initialize max sum as the smallest possible integer let mxSum = [-Infinity]; // Find the target leaf and maximum sum findMaxSum(root, 0, mxSum); // Return the maximum sum found return mxSum[0]; } // Constructing tree: // 10 // / \ // -2 7 // / \ // 8 -4 let root = new Node(10); root.left = new Node(-2); root.right = new Node(7); root.left.left = new Node(8); root.left.right = new Node(-4); let sum = maxPathSum(root); console.log(sum);
Time Complexity: O(n) Where n is number of nodes in tree.
Auxiliary Space: O(n) , Function call stack space.
Related articles:
Similar Reads
Maximize sum of path from the Root to a Leaf node in N-ary Tree
Given a generic tree consisting of n nodes, the task is to find the maximum sum of the path from the root to the leaf node. Examples: Input: Output: 12Explanation: The path sum to every leaf from the root are:For node 4: 1 -> 2 -> 4 = 7For node 5: 1 -> 2 -> 5 = 8For node 6: 1 -> 3 -
5 min read
Find all root to leaf path sum of a Binary Tree
Given a Binary Tree, the task is to print all the root to leaf path sum of the given Binary Tree. Examples: Input: 30 / \ 10 50 / \ / \ 3 16 40 60 Output: 43 56 120 140 Explanation: In the above binary tree there are 4 leaf nodes. Hence, total 4 path sum are present from root node to the leaf node.
8 min read
Maximize count of set bits in a root to leaf path in a binary tree
Given a binary tree, the task is to find the total count of set bits in the node values of all the root to leaf paths and print the maximum among them. Examples: Input: Output: 12Explanation:Path 1: 15(1111)->3(0011)->5(0101) = 8Path 2: 15(1111)->3(0011)->1(0001) = 7Path 3: 15(01111)-
6 min read
Maximum Path Sum in a Binary Tree
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: 42Explanation: Max path sum is represented using green colour nodes in the above binary tree. Input: Output: 31Explanation: Max path sum is represented using gre
9 min read
Find maximum GCD value from root to leaf in a Binary tree
Given a Binary Tree, the task is to find the maximum value of GCD from any path from the root node to the leaf node. Examples: Input: Below is the given tree: Output: 3Explanation:Path 1: 15->3->5 = gcd(15, 3, 15) =3Path 2: 15->3->1 =gcd(15, 3, 1) = 1Path 3: 15->7->31=gcd(15, 7, 31
8 min read
Print the first shortest root to leaf path in a Binary Tree
Given a Binary Tree with distinct values, the task is to find the first smallest root to leaf path. We basically need to find the leftmost root to leaf path that has the minimum number of nodes. The root to leaf path in below image is 1-> 3 which is the leftmost root to leaf path that has the min
8 min read
Find maximum level sum in Binary Tree
Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum level in it. Examples: Input : 4 / \ 2 -5 / \ /\ -1 3 -2 6Output: 6Explanation :Sum of all nodes of 0'th level is 4Sum of all nodes of 1'th level is -3Sum of all nodes of 0'th level is 6Hence maximum sum is 6
15+ 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
Print the longest leaf to leaf path in a Binary tree
C/C++ Code // C++ program to print the longest leaf to leaf // path #include <bits/stdc++.h> using namespace std; // Tree node structure used in the program struct Node { int data; Node *left, *right; }; struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node-
15+ min read
Print Root-to-Leaf Paths in a Binary Tree
Given a Binary Tree of nodes, the task is to find all the possible paths from the root node to all the leaf nodes of the binary tree. Example: Input: Output: 1 2 41 2 51 3 Using Recursion - O(n) Time and O(h) SpaceIn the recursive approach to print all paths from the root to leaf nodes, we can perfo
2 min read