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 DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
DP on Trees | Set-3 ( Diameter of N-ary Tree )
Next article icon

Introduction to Dynamic Programming on Trees

Last Updated : 04 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Introduction-to-Dynamic-Programming-on-Trees

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 and take 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:

  • maxSumPath(node) = node->data + max(maxSumPath(node->left), maxSumPath(node->right))

Base Case:

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> using namespace std;  class Node {   public:     int data;     Node *left;     Node *right;      Node(int x) {         data = x;         left = right = nullptr;     } };  // Helper function to find maximum sum path void maxSumPath(Node *node, int currentSum, int &maxSum) {     if (node == nullptr) {         return;     }      // Add current node's data to the path sum     currentSum += node->data;      // Check if leaf node is reached, update maxSum     if (node->left == nullptr && node->right == nullptr) {         if (currentSum > maxSum) {             maxSum = currentSum;         }     }     else {                // Recurse for left and right subtrees         maxSumPath(node->left, currentSum, maxSum);         maxSumPath(node->right, currentSum, maxSum);     } }  // Function to get the maximum sum from root to any leaf int maxRootToLeafSum(Node *root) {     int maxSum = 0;     maxSumPath(root, 0, maxSum);     return maxSum; }  int main() {        // Harcoded binary tree     //        1     //       / \      //      2   3      //     /\   /     //    4  5 6      Node *root = new Node(1);     root->left = new Node(2);     root->right = new Node(3);     root->left->left = new Node(4);     root->left->right = new Node(5);     root->right->left = new Node(6);      cout << maxRootToLeafSum(root) << endl;      return 0; } 
Java
// Java code to calculate the maximum sum from root  // to leaf node using recursion. import java.util.*;  class Node {     int data;     Node left, right;      Node(int x) {         data = x;         left = right = null;     } }  class GfG {        static void maxSumPath(Node node, int currentSum,                                         int[] maxSum) {         if (node == null) {             return;         }          // Add current node's data to the path sum         currentSum += node.data;          // Check if leaf node is reached, update maxSum         if (node.left == null && node.right == null) {             if (currentSum > maxSum[0]) {                 maxSum[0] = currentSum;             }         }          else {                        // Recurse for left and right subtrees             maxSumPath(node.left, currentSum, maxSum);             maxSumPath(node.right, currentSum, maxSum);         }     }      // Function to get the maximum sum from     // root to any leaf     static int maxRootToLeafSum(Node root) {         int[] maxSum = {0};         maxSumPath(root, 0, maxSum);         return maxSum[0];     }      public static void main(String[] args) {                // Hardcoded binary tree         //        1         //       / \          //      2   3          //     /\   /         //    4  5 6          Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);         root.right.left = new Node(6);                System.out.print(maxRootToLeafSum(root));     } } 
Python
# Python code to calculate the maximum sum from root  # to leaf node using recursion. class Node:     def __init__(self, x):         self.data = x         self.left = None         self.right = None  # Helper function to find maximum sum path def max_sum_path(node, current_sum, max_sum):     if node is None:         return      # Add current node's data to the path sum     current_sum += node.data      # Check if leaf node is reached, update max_sum     if node.left is None and node.right is None:         max_sum[0] = max(max_sum[0], current_sum)     else:                # Recurse for left and right subtrees         max_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 leaf def max_root_to_leaf_sum(root):     max_sum = [0]     max_sum_path(root, 0, max_sum)     return max_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. 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 maximum sum path     static void MaxSumPath(Node node,                               int currentSum, int[] maxSum) {         if (node == null) {             return;         }          // Add current node's data to the path sum         currentSum += node.data;          // Check if leaf node is reached, update maxSum         if (node.left == null && node.right == null) {             if (currentSum > maxSum[0]) {                 maxSum[0] = currentSum;             }         }         else {                       // Recurse for left and right subtrees             MaxSumPath(node.left, currentSum, maxSum);             MaxSumPath(node.right, currentSum, maxSum);         }     }      // Function to get the maximum sum from root to any leaf     static int MaxRootToLeafSum(Node root) {         int[] maxSum = {0};         MaxSumPath(root, 0, maxSum);         return maxSum[0];     }      static void Main(string[] args) {                // Hardcoded binary tree         //        1         //       / \          //      2   3          //     / \  /         //    4   5 6          Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);         root.right.left = new Node(6);          Console.WriteLine(MaxRootToLeafSum(root));     } } 
JavaScript
// JavaScript code to calculate the maximum sum   // from root to leaf node using recursion. class Node {     constructor(data) {         this.data = data;         this.left = null;         this.right = null;     } }  // Helper function to find the maximum sum path function maxSumPath(node, currentSum, maxSum) {     if (node === null) {         return;     }      // Add current node's data to the path sum     currentSum += node.data;      // Check if leaf node is reached, update maxSum     if (node.left === null && node.right === null) {         if (currentSum > maxSum[0]) {             maxSum[0] = currentSum;         }     } else {              // Recurse for left and right subtrees         maxSumPath(node.left, currentSum, maxSum);         maxSumPath(node.right, currentSum, maxSum);     } }  // Function to get the maximum sum from root to any leaf function maxRootToLeafSum(root) {     let maxSum = [0];     maxSumPath(root, 0, maxSum);     return maxSum[0]; }  // Hardcoded binary tree //        1 //       / \  //      2   3  //     / \  / //    4   5 6  const root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(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]
Introduction-to-Dynamic-Programming-on-Trees-2
C++
// C++ code to calculate the maximum sum from root  // to leaf node using recursion and memoization. #include <iostream> #include <unordered_map> using namespace std;  class Node {   public:     int data;     Node *left;     Node *right;      Node(int x) {         data = x;         left = right = nullptr;     } };  // Helper function to find maximum sum path with memoization int maxSumPath(Node *node, unordered_map<Node*, int> &memo) {     if (node == nullptr) {         return 0;     }      // Check if the result is already in memo     if (memo.find(node) != memo.end()) {         return memo[node];     }      // If it's a leaf node, the maximum sum is its own data     if (node->left == nullptr && node->right == nullptr) {         return memo[node] = node->data;     }      // Recurse for left and right subtrees and      // choose the maximum path     int leftSum = maxSumPath(node->left, memo);     int rightSum = maxSumPath(node->right, memo);      // Store the computed result in memo     memo[node] = node->data + max(leftSum, rightSum);     return memo[node]; }  // Function to get the maximum sum from root to any leaf int maxRootToLeafSum(Node *root) {     unordered_map<Node*, int> memo;     return maxSumPath(root, memo); }  int main() {        // Hardcoded binary tree     //        1     //       / \      //      2   3      //     /\   /     //    4  5 6      Node *root = new Node(1);     root->left = new Node(2);     root->right = new Node(3);     root->left->left = new Node(4);     root->left->right = new Node(5);     root->right->left = new Node(6);      cout << maxRootToLeafSum(root) << endl;      return 0; } 
Java
// Java code to calculate the maximum sum from root  // to leaf node using recursion and memoization. import java.util.HashMap;  class Node {     int data;     Node left, right;      Node(int x) {         data = x;         left = right = null;     } }  class GfG {      // Helper function to find maximum sum path with memoization     static int maxSumPath(Node node,                           HashMap<Node, Integer> memo) {         if (node == null) {             return 0;         }          // Check if the result is already in memo         if (memo.containsKey(node)) {             return memo.get(node);         }          // If it's a leaf node, the maximum sum is its own data         if (node.left == null && node.right == null) {             memo.put(node, node.data);             return node.data;         }          // Recurse for left and right subtrees and          // choose the maximum path         int leftSum = maxSumPath(node.left, memo);         int rightSum = maxSumPath(node.right, memo);          // Store the computed result in memo         int result = node.data + Math.max(leftSum, rightSum);         memo.put(node, result);         return result;     }      // Function to get the maximum sum from root to any leaf     static int maxRootToLeafSum(Node root) {         HashMap<Node, Integer> memo = new HashMap<>();         return maxSumPath(root, memo);     }      public static void main(String[] args) {                // Hardcoded binary tree         //        1         //       / \          //      2   3          //     /\   /         //    4  5 6          Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);         root.right.left = new Node(6);          System.out.print(maxRootToLeafSum(root));     } } 
Python
# Python code to calculate the maximum sum from root # to leaf node recursion and memoization. class Node:     def __init__(self, data):         self.data = data         self.left = None         self.right = None  # Helper function to find maximum sum  # path with memoization def max_sum_path(node, memo):     if node is None:         return 0      # Check if the result is already in memo     if node in memo:         return memo[node]      # If it's a leaf node, the maximum sum      # is its own data     if node.left is None and node.right is None:         memo[node] = node.data         return memo[node]      # Recurse for left and right subtrees and      # choose the maximum path     left_sum = max_sum_path(node.left, memo)     right_sum = max_sum_path(node.right, memo)      # Store the computed result in memo     memo[node] = node.data + max(left_sum, right_sum)     return memo[node]  # Function to get the maximum sum from root to any leaf def max_root_to_leaf_sum(root):     memo = {}     return max_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. 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 find maximum sum path with memoization     static int MaxSumPath(Node node, Dictionary<Node, int> memo) {         if (node == null) {             return 0;         }          // Check if the result is already in memo         if (memo.ContainsKey(node)) {             return memo[node];         }          // If it's a leaf node, the maximum sum is its own data         if (node.left == null && node.right == null) {             memo[node] = node.data;             return node.data;         }          // Recurse for left and right subtrees and choose the maximum path         int leftSum = MaxSumPath(node.left, memo);         int rightSum = MaxSumPath(node.right, memo);          // Store the computed result in memo         int result = node.data + Math.Max(leftSum, rightSum);         memo[node] = result;         return result;     }      // Function to get the maximum sum from root to any leaf     static int MaxRootToLeafSum(Node root) {         Dictionary<Node, int> memo                 = new Dictionary<Node, int>();                return MaxSumPath(root, memo);     }      static void Main(string[] args) {                // Hardcoded binary tree         //        1         //       / \          //      2   3          //     /\   /         //    4  5 6          Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);         root.right.left = new Node(6);          Console.WriteLine(MaxRootToLeafSum(root));     } } 
JavaScript
// JavaScript code to calculate the maximum sum from root  // to leaf node using recursion and memoization. class Node {     constructor(data) {         this.data = data;         this.left = null;         this.right = null;     } }  // Helper function to find maximum sum  // path with memoization function maxSumPath(node, memo) {     if (node === null) {         return 0;     }      // Check if the result is already in memo     if (memo.has(node)) {         return memo.get(node);     }      // If it's a leaf node, the maximum sum is its own data     if (node.left === null && node.right === null) {         memo.set(node, node.data);         return node.data;     }      // Recurse for left and right subtrees and      // choose the maximum path     const leftSum = maxSumPath(node.left, memo);     const rightSum = maxSumPath(node.right, memo);      // Store the computed result in memo     const result = node.data + Math.max(leftSum, rightSum);     memo.set(node, result);     return result; }  // Function to get the maximum sum from root to any leaf function maxRootToLeafSum(root) {     const memo = new Map();     return maxSumPath(root, memo); }  // Hardcoded binary tree //        1 //       / \  //      2   3  //     /\   / //    4  5 6  const root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6);  console.log(maxRootToLeafSum(root)); 

Output
10 

Next Article
DP on Trees | Set-3 ( Diameter of N-ary Tree )

S

Striver
Improve
Article Tags :
  • Misc
  • Tree
  • Algorithms
  • Dynamic Programming
  • Advanced Data Structure
  • DSA
Practice Tags :
  • Advanced Data Structure
  • Algorithms
  • Dynamic Programming
  • Misc
  • Tree

Similar Reads

    DP on Trees for Competitive Programming
    Dynamic Programming (DP) on trees is a powerful algorithmic technique commonly used in competitive programming. It involves solving various tree-related problems by efficiently calculating and storing intermediate results to optimize time complexity. By using the tree structure, DP on trees allows p
    15+ min read
    Introduction to Dynamic Programming on Trees
    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 bin
    13 min read
    DP on Trees | Set-3 ( Diameter of N-ary Tree )
    Given an N-ary tree, the task is to calculate the longest path between any two nodes (also known as the diameter of the tree).Examples: Example1: The diameter of the N-ary tree in the below example is 9, which represents the number of edges along the path marked with green nodes. Example2: The diame
    8 min read
    Maximum height of Tree when any Node can be considered as Root
    Given a tree with n nodes and n-1 edges, the task is to find the maximum height of the tree when any node in the tree is considered as the root of the tree. Example:Input: Output: 5Explanation: The below diagram represents a tree with 11 nodes and 10 edges and the path that gives us the maximum heig
    15+ min read
    Maximal Point Path
    Given a tree with N nodes numbered from 1 to N. Each Node has a value denoting the number of points you get when you visit that Node. Each edge has a length and as soon as you travel through this edge number of points is reduced by the length of the edge, the task is to choose two nodes u and v such
    14 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