Dynamic Programming is a technique to solve problems by breaking them down into overlapping sub-problems which follows the optimal substructure. There are various problems using DP like subset sum, knapsack, coin change etc. DP can also be applied to trees to solve some specific problems. Given a binary tree with n nodes and n-1 edges, calculate the maximum sum of the node values from the root to any of the leaves without re-visiting any node.
Examples:
Input:
Output: 22 Explanation: Given above is a diagram of a tree with n = 14 nodes and n-1 = 13 edges.The below shows all the paths from root to leaves:
3 -> 2 -> 1 -> 4: sum of all node values = 10
3 -> 2 -> 1 -> 5: sum of all node values = 11
3 -> 2 -> 3: sum of all node values = 8
3 -> 1 -> 9 -> 9: sum of all node values = 22
3 -> 1 -> 9 -> 8 : sum of all node values = 21
3 -> 10 -> 1: sum of all node values = 14
3 -> 10 -> 5 : sum of all node values = 18
3 -> 10 -> 3 : sum of all node values = 16
The answer is 22, as Path 4 has the maximum sum of values of nodes in its path from a root to leaves.
The greedy approach fails in this case. Starting from the root andtake 3 from the first level, 10 from the next level and 5 from the third level greedily. Result is path -7 if after following the greedy approach, hence do not apply greedy approach over here.
Using Recursion - O(n) Time and O(h) Space
For the recursive approach, the task is to calculate the maximum sum from the root to any leaf node. At each node, there are two cases:
Add the value of the current node to the currentSum and proceed to its left and right children recursively.
If the node is a leaf (both left and right children are null), compare the currentSum with the maxSum. Update maxSum if currentSum is greater.
Mathematically, the recurrence relation can be expressed as:
If the current node is nullptr, return from the recursion (no addition to the sum is possible).
C++
// C++ code to calculate the maximum sum from root // to leaf node using recursion.#include<iostream>#include<vector>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Helper function to find maximum sum pathvoidmaxSumPath(Node*node,intcurrentSum,int&maxSum){if(node==nullptr){return;}// Add current node's data to the path sumcurrentSum+=node->data;// Check if leaf node is reached, update maxSumif(node->left==nullptr&&node->right==nullptr){if(currentSum>maxSum){maxSum=currentSum;}}else{// Recurse for left and right subtreesmaxSumPath(node->left,currentSum,maxSum);maxSumPath(node->right,currentSum,maxSum);}}// Function to get the maximum sum from root to any leafintmaxRootToLeafSum(Node*root){intmaxSum=0;maxSumPath(root,0,maxSum);returnmaxSum;}intmain(){// Harcoded binary tree// 1// / \ // 2 3 // /\ /// 4 5 6 Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);cout<<maxRootToLeafSum(root)<<endl;return0;}
Java
// Java code to calculate the maximum sum from root // to leaf node using recursion.importjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{staticvoidmaxSumPath(Nodenode,intcurrentSum,int[]maxSum){if(node==null){return;}// Add current node's data to the path sumcurrentSum+=node.data;// Check if leaf node is reached, update maxSumif(node.left==null&&node.right==null){if(currentSum>maxSum[0]){maxSum[0]=currentSum;}}else{// Recurse for left and right subtreesmaxSumPath(node.left,currentSum,maxSum);maxSumPath(node.right,currentSum,maxSum);}}// Function to get the maximum sum from// root to any leafstaticintmaxRootToLeafSum(Noderoot){int[]maxSum={0};maxSumPath(root,0,maxSum);returnmaxSum[0];}publicstaticvoidmain(String[]args){// Hardcoded binary tree// 1// / \ // 2 3 // /\ /// 4 5 6 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);System.out.print(maxRootToLeafSum(root));}}
Python
# Python code to calculate the maximum sum from root # to leaf node using recursion.classNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Helper function to find maximum sum pathdefmax_sum_path(node,current_sum,max_sum):ifnodeisNone:return# Add current node's data to the path sumcurrent_sum+=node.data# Check if leaf node is reached, update max_sumifnode.leftisNoneandnode.rightisNone:max_sum[0]=max(max_sum[0],current_sum)else:# Recurse for left and right subtreesmax_sum_path(node.left,current_sum,max_sum)max_sum_path(node.right,current_sum,max_sum)# Function to get the maximum sum from root to any leafdefmax_root_to_leaf_sum(root):max_sum=[0]max_sum_path(root,0,max_sum)returnmax_sum[0]if__name__=="__main__":# Hardcoded binary tree# 1# / \ # 2 3 # / \ /# 4 5 6 root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)print(max_root_to_leaf_sum(root))
C#
// C# code to calculate the maximum sum from root // to leaf node using recursion.usingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Helper function to find maximum sum pathstaticvoidMaxSumPath(Nodenode,intcurrentSum,int[]maxSum){if(node==null){return;}// Add current node's data to the path sumcurrentSum+=node.data;// Check if leaf node is reached, update maxSumif(node.left==null&&node.right==null){if(currentSum>maxSum[0]){maxSum[0]=currentSum;}}else{// Recurse for left and right subtreesMaxSumPath(node.left,currentSum,maxSum);MaxSumPath(node.right,currentSum,maxSum);}}// Function to get the maximum sum from root to any leafstaticintMaxRootToLeafSum(Noderoot){int[]maxSum={0};MaxSumPath(root,0,maxSum);returnmaxSum[0];}staticvoidMain(string[]args){// Hardcoded binary tree// 1// / \ // 2 3 // / \ /// 4 5 6 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);Console.WriteLine(MaxRootToLeafSum(root));}}
JavaScript
// JavaScript code to calculate the maximum sum // from root to leaf node using recursion.classNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Helper function to find the maximum sum pathfunctionmaxSumPath(node,currentSum,maxSum){if(node===null){return;}// Add current node's data to the path sumcurrentSum+=node.data;// Check if leaf node is reached, update maxSumif(node.left===null&&node.right===null){if(currentSum>maxSum[0]){maxSum[0]=currentSum;}}else{// Recurse for left and right subtreesmaxSumPath(node.left,currentSum,maxSum);maxSumPath(node.right,currentSum,maxSum);}}// Function to get the maximum sum from root to any leaffunctionmaxRootToLeafSum(root){letmaxSum=[0];maxSumPath(root,0,maxSum);returnmaxSum[0];}// Hardcoded binary tree// 1// / \ // 2 3 // / \ /// 4 5 6 constroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);console.log(maxRootToLeafSum(root));
Output
10
Using Top-Down DP (Memoization) - O(n) Time and O(n) Space
1. Optimal Substructure: The solution to the maximum sum problem can be derived from the optimal solutions of smaller subproblems. At any given node, the maximum path sum is the sum of the node’s value and the maximum of the sums obtained from its left and right children.
2. Overlapping Subproblems: The maximum sum for a node may be recomputed multiple times. Using a memoization table we:
Check if the result for a node exists.If not, compute and store it.
This avoids redundant calculations and ensures each node is processed once.
Memoization Condition: If the result for the current node is already stored in the memoization table:
if memo[node] exists, return memo[node]
C++
// C++ code to calculate the maximum sum from root // to leaf node using recursion and memoization.#include<iostream>#include<unordered_map>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Helper function to find maximum sum path with memoizationintmaxSumPath(Node*node,unordered_map<Node*,int>&memo){if(node==nullptr){return0;}// Check if the result is already in memoif(memo.find(node)!=memo.end()){returnmemo[node];}// If it's a leaf node, the maximum sum is its own dataif(node->left==nullptr&&node->right==nullptr){returnmemo[node]=node->data;}// Recurse for left and right subtrees and // choose the maximum pathintleftSum=maxSumPath(node->left,memo);intrightSum=maxSumPath(node->right,memo);// Store the computed result in memomemo[node]=node->data+max(leftSum,rightSum);returnmemo[node];}// Function to get the maximum sum from root to any leafintmaxRootToLeafSum(Node*root){unordered_map<Node*,int>memo;returnmaxSumPath(root,memo);}intmain(){// Hardcoded binary tree// 1// / \ // 2 3 // /\ /// 4 5 6 Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);cout<<maxRootToLeafSum(root)<<endl;return0;}
Java
// Java code to calculate the maximum sum from root // to leaf node using recursion and memoization.importjava.util.HashMap;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Helper function to find maximum sum path with memoizationstaticintmaxSumPath(Nodenode,HashMap<Node,Integer>memo){if(node==null){return0;}// Check if the result is already in memoif(memo.containsKey(node)){returnmemo.get(node);}// If it's a leaf node, the maximum sum is its own dataif(node.left==null&&node.right==null){memo.put(node,node.data);returnnode.data;}// Recurse for left and right subtrees and // choose the maximum pathintleftSum=maxSumPath(node.left,memo);intrightSum=maxSumPath(node.right,memo);// Store the computed result in memointresult=node.data+Math.max(leftSum,rightSum);memo.put(node,result);returnresult;}// Function to get the maximum sum from root to any leafstaticintmaxRootToLeafSum(Noderoot){HashMap<Node,Integer>memo=newHashMap<>();returnmaxSumPath(root,memo);}publicstaticvoidmain(String[]args){// Hardcoded binary tree// 1// / \ // 2 3 // /\ /// 4 5 6 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);System.out.print(maxRootToLeafSum(root));}}
Python
# Python code to calculate the maximum sum from root# to leaf node recursion and memoization.classNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Helper function to find maximum sum # path with memoizationdefmax_sum_path(node,memo):ifnodeisNone:return0# Check if the result is already in memoifnodeinmemo:returnmemo[node]# If it's a leaf node, the maximum sum # is its own dataifnode.leftisNoneandnode.rightisNone:memo[node]=node.datareturnmemo[node]# Recurse for left and right subtrees and # choose the maximum pathleft_sum=max_sum_path(node.left,memo)right_sum=max_sum_path(node.right,memo)# Store the computed result in memomemo[node]=node.data+max(left_sum,right_sum)returnmemo[node]# Function to get the maximum sum from root to any leafdefmax_root_to_leaf_sum(root):memo={}returnmax_sum_path(root,memo)if__name__=="__main__":# Hardcoded binary tree# 1# / \ # 2 3 # /\ /# 4 5 6 root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)print(max_root_to_leaf_sum(root))
C#
// C# code to calculate the maximum sum from root// to leaf node using recursion and memoization.usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Helper function to find maximum sum path with memoizationstaticintMaxSumPath(Nodenode,Dictionary<Node,int>memo){if(node==null){return0;}// Check if the result is already in memoif(memo.ContainsKey(node)){returnmemo[node];}// If it's a leaf node, the maximum sum is its own dataif(node.left==null&&node.right==null){memo[node]=node.data;returnnode.data;}// Recurse for left and right subtrees and choose the maximum pathintleftSum=MaxSumPath(node.left,memo);intrightSum=MaxSumPath(node.right,memo);// Store the computed result in memointresult=node.data+Math.Max(leftSum,rightSum);memo[node]=result;returnresult;}// Function to get the maximum sum from root to any leafstaticintMaxRootToLeafSum(Noderoot){Dictionary<Node,int>memo=newDictionary<Node,int>();returnMaxSumPath(root,memo);}staticvoidMain(string[]args){// Hardcoded binary tree// 1// / \ // 2 3 // /\ /// 4 5 6 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);Console.WriteLine(MaxRootToLeafSum(root));}}
JavaScript
// JavaScript code to calculate the maximum sum from root // to leaf node using recursion and memoization.classNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Helper function to find maximum sum // path with memoizationfunctionmaxSumPath(node,memo){if(node===null){return0;}// Check if the result is already in memoif(memo.has(node)){returnmemo.get(node);}// If it's a leaf node, the maximum sum is its own dataif(node.left===null&&node.right===null){memo.set(node,node.data);returnnode.data;}// Recurse for left and right subtrees and // choose the maximum pathconstleftSum=maxSumPath(node.left,memo);constrightSum=maxSumPath(node.right,memo);// Store the computed result in memoconstresult=node.data+Math.max(leftSum,rightSum);memo.set(node,result);returnresult;}// Function to get the maximum sum from root to any leaffunctionmaxRootToLeafSum(root){constmemo=newMap();returnmaxSumPath(root,memo);}// Hardcoded binary tree// 1// / \ // 2 3 // /\ /// 4 5 6 constroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);console.log(maxRootToLeafSum(root));
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
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.