The Wayback Machine - https://web.archive.org/web/20240819104123/https://www.geeksforgeeks.org/maximum-sum-of-nodes-in-binary-tree-such-that-no-two-are-adjacent-dynamic-programming/
Open In App

Maximum sum of nodes in Binary tree such that no two are adjacent | Dynamic Programming

Last Updated : 30 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a N-ary tree with a value associated with each node, the task is to choose a subset of these nodes such that sum of chosen nodes is maximum under a constraint that no two chosen node in subset should be directly connected that is, if we have taken a node in our sum then we can’t take its any children in consideration and vice versa.
Examples: 
 

The above diagram selects the nodes with a deep green color to get the maximum value 25. 
 

An approach to this problem has been discussed in the previous post using recursion. 
In this post, we will be discussing an approach using Dynamic Programming on Trees. 
While solving the problem, there arise two cases: 

  1. For a particular node, the maximum sum can be calculated by including the node itself along with nodes from its subtree.
  2. Or, the maximum sum is calculated by excluding the current node and including only the nodes from its subtree.

Let us assume: 

  • dp1[node] to be the maximum possible sum by choosing nodes from the subtree of this node and also including the node.
  • And, dp2[node] to be the maximum possible sum by choosing nodes from the subtree of the node and not including the node itself.

In the first case, if we include the current node, then its value is added and then we can not include any of its immediate children, hence the summation of dp2[] of all the children will be taken into the count to compute dp1[node]. That is, 
 

dp1[node] = tree[node] + sum(dp2[children1], dp2[children2], …) 

In the second case, if we do not include the current node, then its value is not added, but the children node can be taken or it cannot be taken, hence the summation of the maximum of both for all the children will be taken into count to compute dp2[node]. That is, 
 

dp2[node] = tree[node] + sum(max(dp1[children1], dp2[children1]), max(dp1[children2], dp2[children2])…) 

In the end, the final answer will be the maximum of dp1[root] and dp2[root]. 
Below is the implementation of the above approach: 
 

C++




// C++ program to find maximum sum
// of a subset of nodes that are not adjacent
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the diameter of the tree
// using Dynamic Programming
void dfs(int node, int parent, int dp1[], int dp2[],
                            list<int>* adj, int tree[])
{
 
    int sum1 = 0, sum2 = 0;
 
    // Traverse for all children of node
    for (auto i = adj[node].begin(); i != adj[node].end(); ++i) {
        if (*i == parent)
            continue;
 
        // Call DFS function again
        dfs(*i, node, dp1, dp2, adj, tree);
 
        // Include the current node
        // then donot include the children
        sum1 += dp2[*i];
 
        // Donot include current node,
        // then include children or not include them
        sum2 += max(dp1[*i], dp2[*i]);
    }
 
    // Recurrence value
    dp1[node] = tree[node] + sum1;
    dp2[node] = sum2;
}
 
/* Driver program to test above functions */
int main()
{
    int n = 5;
 
    /* Constructed tree is
        1
        / \
        2 3
       / \
       4 5 */
    list<int>* adj = new list<int>[n + 1];
 
    /* create undirected edges */
    adj[1].push_back(2);
    adj[2].push_back(1);
    adj[1].push_back(3);
    adj[3].push_back(1);
    adj[2].push_back(4);
    adj[4].push_back(2);
    adj[2].push_back(5);
    adj[5].push_back(2);
 
    // Numbers to node
    int tree[n + 1];
    tree[1] = 10;
    tree[2] = 5;
    tree[3] = 11;
    tree[4] = 6;
    tree[5] = 8;
 
    int dp1[n + 1], dp2[n + 1];
    memset(dp1, 0, sizeof dp1);
    memset(dp2, 0, sizeof dp2);
 
    dfs(1, 1, dp1, dp2, adj, tree);
 
    // Find maximum sum by calling function
    cout << "Maximum sum: "
         << max(dp1[1], dp2[1]) << endl;
    return 0;
}


Java




import java.util.*;
public class Main {
  public static void
    dfs(int node, int parent, int[] dp1, int[] dp2,
        ArrayList<ArrayList<Integer> > adj, int[] tree)
  {
 
    int sum1 = 0, sum2 = 0;
 
    // Traverse for all children of node
    for (int j = 0; j < adj.get(node).size(); j++) {
      int i = adj.get(node).get(j);
      if (i == parent)
        continue;
 
      // Call DFS function again
      dfs(i, node, dp1, dp2, adj, tree);
 
      // Include the current node
      // then donot include the children
      sum1 += dp2[i];
 
      // Donot include current node,
      // then include children or not include them
      sum2 += Math.max(dp1[i], dp2[i]);
    }
 
    // Recurrence value
    dp1[node] = tree[node] + sum1;
    dp2[node] = sum2;
  }
  public static void main(String[] args)
  {
    int n = 5;
 
    /* Constructed tree is
            1
            / \
            2 3
           / \
           4 5 */
 
    ArrayList<ArrayList<Integer> > adj
      = new ArrayList<ArrayList<Integer> >();
    for (int i = 0; i < n + 1; i++) {
      adj.add(new ArrayList<Integer>());
    }
 
    /* create undirected edges */
    adj.get(1).add(2);
    adj.get(2).add(1);
    adj.get(1).add(3);
    adj.get(3).add(1);
    adj.get(2).add(4);
    adj.get(4).add(2);
    adj.get(2).add(5);
    adj.get(5).add(2);
 
    // Numbers to node
    int[] tree = new int[n + 1];
    tree[1] = 10;
    tree[2] = 5;
    tree[3] = 11;
    tree[4] = 6;
    tree[5] = 8;
 
    int[] dp1 = new int[n + 1];
    int[] dp2 = new int[n + 1];
 
    dfs(1, 1, dp1, dp2, adj, tree);
 
    // Find maximum sum by calling function
    System.out.println("Maximum sum: "
                       + Math.max(dp1[1], dp2[1]));
  }
}
 
// This code is contributed by garg28harsh.


Python3




# Python3 program to find
# maximum sum of a subset
# of nodes that are not
# adjacent
 
# Function to find the diameter
# of the tree using Dynamic
# Programming
def dfs(node, parent, dp1,
        dp2, adj, tree):
  
    sum1 = 0
    sum2 = 0
  
    # Traverse for all
    # children of node
    for i in adj[node]:   
        if (i == parent):
            continue;
  
        # Call DFS function
        # again
        dfs(i, node, dp1,
            dp2, adj, tree);
  
        # Include the current
        # node then donot include
        # the children
        sum1 += dp2[i];
  
        # Donot include current node,
        # then include children or not
        # include them
        sum2 += max(dp1[i],
                    dp2[i]);   
  
    # Recurrence value
    dp1[node] = tree[node] + sum1;
    dp2[node] = sum2;
 
# Driver code
if __name__=="__main__":
     
    n = 5;
     
    ''' Constructed tree is
        1
        / \
        2 3
       / \
       4 5 '''
        
    adj = [[] for i in range(n + 1)]
  
    # create undirected edges
    adj[1].append(2);
    adj[2].append(1);
    adj[1].append(3);
    adj[3].append(1);
    adj[2].append(4);
    adj[4].append(2);
    adj[2].append(5);
    adj[5].append(2);
  
    # Numbers to node
    tree = [0 for i in range(n + 1)];
    tree[1] = 10;
    tree[2] = 5;
    tree[3] = 11;
    tree[4] = 6;
    tree[5] = 8;
  
    dp1 = [0 for i in range(n + 1)];
    dp2 = [0 for i in range(n + 1)];
  
    dfs(1, 1, dp1, dp2, adj, tree);
  
    # Find maximum sum by calling
    # function
    print("Maximum sum:",
          max(dp1[1], dp2[1]))
     
# This code is contributed by Rutvik_56


C#




// C# program to find maximum sum
// of a subset of nodes that are not adjacent
using System;
using System.Collections;
 
class GFG
{
 
// Function to find the diameter of the tree
// using Dynamic Programming
public static void dfs(int node, int parent, int []dp1, int []dp2,
                            ArrayList []adj, int []tree)
{
  
    int sum1 = 0, sum2 = 0;
  
    // Traverse for all children of node
    foreach(int i in adj[node])
    {
        if (i == parent)
            continue;
  
        // Call DFS function again
        dfs(i, node, dp1, dp2, adj, tree);
  
        // Include the current node
        // then donot include the children
        sum1 += dp2[i];
  
        // Donot include current node,
        // then include children or not include them
        sum2 += Math.Max(dp1[i], dp2[i]);
    }
  
    // Recurrence value
    dp1[node] = tree[node] + sum1;
    dp2[node] = sum2;
}
  
/* Driver program to test above functions */
public static void Main(string []arg)
{
    int n = 5;
  
    /* Constructed tree is
        1
        / \
        2 3
       / \
       4 5 */
    ArrayList []adj = new ArrayList[n + 1];
     
    for(int i = 0; i < n + 1; i++)
    {
        adj[i] = new ArrayList();
    }
  
    /* create undirected edges */
    adj[1].Add(2);
    adj[2].Add(1);
    adj[1].Add(3);
    adj[3].Add(1);
    adj[2].Add(4);
    adj[4].Add(2);
    adj[2].Add(5);
    adj[5].Add(2);
  
    // Numbers to node
    int []tree = new int[n + 1];
    tree[1] = 10;
    tree[2] = 5;
    tree[3] = 11;
    tree[4] = 6;
    tree[5] = 8;
  
    int []dp1 = new int[n + 1];
    int []dp2 = new int[n + 1];
    Array.Fill(dp1, 0);
    Array.Fill(dp2, 0);
  
    dfs(1, 1, dp1, dp2, adj, tree);
  
    // Find maximum sum by calling function
    Console.Write("Maximum sum: "+ Math.Max(dp1[1], dp2[1]));
}
}
 
// This code is contributed by pratham76


Javascript




<script>
 
// Python3 program to find
// maximum sum of a subset
// of nodes that are not
// adjacent
 
// Function to find the diameter
// of the tree using Dynamic
// Programming
function dfs(node, parent, dp1,dp2, adj, tree){
  
    let sum1 = 0
    let sum2 = 0
  
    // Traverse for all
    // children of node
    for(let i of adj[node]){ 
        if (i == parent)
            continue;
  
        // Call DFS function
        // again
        dfs(i, node, dp1,
            dp2, adj, tree);
  
        // Include the current
        // node then donot include
        // the children
        sum1 += dp2[i];
  
        // Donot include current node,
        // then include children or not
        // include them
        sum2 += Math.max(dp1[i],
                    dp2[i]);   
    }
  
    // Recurrence value
    dp1[node] = tree[node] + sum1;
    dp2[node] = sum2;
}
 
// Driver code
     
    let n = 5;
     
    //  Constructed tree is
    //     1
    //     / \
    //     2 3
    //    / \
    //    4 5
        
    let adj = new Array(n+1);
    for(let i=0;i<n+1;i++){
      adj[i] = new Array();
    }
  
    // create undirected edges
    adj[1].push(2);
    adj[2].push(1);
    adj[1].push(3);
    adj[3].push(1);
    adj[2].push(4);
    adj[4].push(2);
    adj[2].push(5);
    adj[5].push(2);
  
    // Numbers to node
    let tree = new Array(n+1).fill(0);
    tree[1] = 10;
    tree[2] = 5;
    tree[3] = 11;
    tree[4] = 6;
    tree[5] = 8;
  
    let dp1 = new Array(n+1).fill(0);
    let dp2 = new Array(n+1).fill(0);
  
    dfs(1, 1, dp1, dp2, adj, tree);
  
    // Find maximum sum by calling
    // function
    document.write("Maximum sum: ", Math.max(dp1[1], dp2[1]),"</br>")
     
// This code is contributed by shinjanpatra
 
</script>


Output: 

Maximum sum: 25

 

Time Complexity: O(N), as we are using recursion to traverse the tree. Where N is the number of nodes in the tree.

Auxiliary Space: O(N), as we are using extra space for the array dp.



Similar Reads

Maximum sum of nodes in Binary tree such that no two are adjacent
Given a binary tree with a value associated with each node, we need to choose a subset of these nodes such that the sum of selected nodes is maximum under a constraint that no two chosen nodes in the subset should be directly connected, that is, if we have taken a node in our sum then we can’t take any of its children in consideration and vice vers
15+ min read
Shortest path length between two given nodes such that adjacent nodes are at bit difference 2
Given an unweighted and undirected graph consisting of N nodes and two integers a and b. The edge between any two nodes exists only if the bit difference between them is 2, the task is to find the length of the shortest path between the nodes a and b. If a path does not exist between the nodes a and b, then print -1. Examples: Input: N = 15, a = 15
7 min read
Find a set of at most N/2 nodes from a Graph such that all remaining nodes are directly connected to one of the chosen nodes
Given an integer N, representing the number of nodes present in an undirected graph, with each node valued from 1 to N, and a 2D array Edges[][], representing the pair of vertices connected by an edge, the task is to find a set of at most N/2 nodes such that nodes that are not present in the set, are connected adjacent to any one of the nodes prese
12 min read
Count of nodes in given N-ary tree such that their subtree is a Binary Tree
Given an N-ary tree root, the task is to find the count of nodes such that their subtree is a binary tree. Example: Input: Tree in the image below Output: 11Explanation: The nodes such that there subtree is a binary tree are {2, 8, 10, 6, 7, 3, 1, 9, 5, 11, 12}. Input: Tree in the image below Output: 9 Approach: The given problem can be solved by u
11 min read
Sum of nodes in a binary tree having only the left child nodes
Given a binary tree, the task is to find the sum of binary tree nodes having only the left child nodes. Example: Input: 8 / \ 3 7 / \ / 5 6 0 / / 1 2Output: 18 Explanation: Nodes with values 5, 6, and 7 are the ones that have only the left child nodes Input: 2 / \ 3 1 / / 5 6Output: 4 Approach: The given problem can be solved by traversing the bina
6 min read
Maximum sum in circular array such that no two elements are adjacent
Given a circular array containing of positive integers value. The task is to find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array. Examples: Input: circular arr = {1, 2, 3, 1} Output : 4 subsequence will be(1, 3), hence 1 + 3 = 4 Input: circular arr = {1, 2, 3, 4, 5, 1} Output:
15+ min read
Maximum sub-sequence sum such that indices of any two adjacent elements differs at least by 3
Given an array arr[] of integers, the task is to find the maximum sum of any sub-sequence in the array such that any two adjacent elements in the selected sequence have at least a difference of 3 in their indices in the given array. In other words, if you select arr[i] then the next element you can select is arr[i + 3], arr[i + 4], and so on... but
12 min read
Maximum sum such that exactly half of the elements are selected and no two adjacent
Given an array A containing N integers. Find the maximum sum possible such that exact floor(N/2) elements are selected and no two selected elements are adjacent to each other. (if N = 5, then exactly 2 elements should be selected as floor(5/2) = 2) For a simpler version of this problem check out this. Examples: Input: A = [1, 2, 3, 4, 5, 6] Output:
14 min read
Maximum sum in circular array such that no two elements are adjacent | Set 2
Given an array arr[] of positive numbers, find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array where the last and the first elements are assumed adjacent. Examples: Input: arr[] = {3, 5, 3} Output: 5 Explanation: We cannot take the first and last elements because they are consid
13 min read
Maximum sum such that no two elements are adjacent | Set 2
Given an array of positive numbers, find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array. So 3 2 7 10 should return 13 (sum of 3 and 10) or 3 2 5 10 7 should return 15 (sum of 3, 5, and 7). Examples: Input : arr[] = {3, 5, 3} Output : 6 Explanation : Selecting indexes 0 and 2 wi
13 min read
Maximum sum such that no two elements are adjacent (Stickler Thief)
Given an array arr[] of positive numbers, The task is to find the maximum sum of a subsequence such that no 2 numbers in the sequence should be adjacent in the array. Examples: Input: arr[] = {5, 5, 10, 100, 10, 5}Output: 110Explanation: Pick the subsequence {5, 100, 5}.The sum is 110 and no two elements are adjacent. This is the highest possible s
15+ min read
Maximum sum in a 2 x n grid such that no two elements are adjacent
Given a rectangular grid of dimension 2 x n. We need to find out the maximum sum such that no two chosen numbers are adjacent, vertically, diagonally, or horizontally. Examples: Input: 1 4 5 2 0 0 Output: 7 If we start from 1 then we can add only 5 or 0. So max_sum = 6 in this case. If we select 2 then also we can add only 5 or 0. So max_sum = 7 in
8 min read
Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
Given a binary tree, change the value in each node to sum of all the values in the nodes in the right subtree including its own. Examples: Input : 1 / \ 2 3 Output : 4 / \ 2 3 Input : 1 / \ 2 3 / \ \ 4 5 6 Output : 10 / \ 7 9 / \ \ 4 5 6 Approach : The idea is to traverse the given binary tree in bottom up manner. Recursively compute the sum of nod
7 min read
Generate Complete Binary Tree in such a way that sum of non-leaf nodes is minimum
Given an array arr[] of size N, the task is to generate a Complete Binary Tree in such a way that sum of the non-leaf nodes is minimum, whereas values of the leaf node corresponds to the array elements in an In-order Traversal of the tree and value of each non-leaf node corresponds to the product of the largest leaf value in the left sub-tree and r
6 min read
Remove nodes from Binary Tree such that sum of all remaining root-to-leaf paths is atleast K
Given a Binary Tree and an integer K, the task is to delete nodes from the given Tree such that the sum of all nodes of all remaining root to leaf paths is at least K. Examples: Input: K = 27 Output: 5 4 8 5 6 11Explanation:Below are the paths whose sum is less than 27: 5 -&gt; 3 -&gt; 9: Path Sum = 5 + 3 + 9 = 17.5 -&gt; 4 -&gt; 9: Path Sum = 5 +
11 min read
Maximum length cycle that can be formed by joining two nodes of a binary tree
Given a binary tree, the task is to find the maximum length of the cycle that can be formed by joining any two nodes of the tree.Examples: Input: 1 / \ 2 3 \ \ 5 6 Output: 5 Cycle can be formed by joining node with value 5 and 6. Input: 1 / \ 3 4 / \ 5 6 / \ 7 8 \ / 11 9 Output: 7 Approach: The idea is to find the diameter of the given binary tree,
5 min read
Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
Given an N-ary tree with weighted edge and Q queries where each query contains two nodes of the tree. The task is to find the maximum weighted edge in the simple path between these two nodes.Examples: Naive Approach: A simple solution is to traverse the whole tree for each query and find the path between the two nodes.Efficient Approach: The idea i
15 min read
Check if max sum level of Binary tree divides tree into two equal sum halves
Given a Binary Tree, the task is to check if the maximum sum level divides the binary tree into the two parts of two equal sum halves.Examples: Input: 1 / \ 2 3 / \ \ 4 5 8 / \ 2 4 Output: YES Explanation: The maximum sum level is 2 and its sum is (4 + 5 + 8 = 17) Sum of the upper half (1 + 2 + 3) = 6 Sum of the Lower half (2 + 4) = 6 Input: 10 / \
11 min read
Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
Given a tree, and the weights (in the form of strings) of all the nodes, the task is to count the nodes whose weighted string when concatenated with the strings of the sub-tree nodes becomes a pangram. Pangram: A pangram is a sentence containing every letter of the English Alphabet. Examples: Input: Output: 1 Only the weighted string of sub-tree of
7 min read
Minimum difference between any two weighted nodes in Sum Tree of the given Tree
Given a tree of N nodes, the task is to convert the given tree to its Sum Tree(including its own weight) and find the minimum difference between any two node's weight of the sum tree. Note: The N nodes of the given tree are given in the form of top to bottom with N-1 line where each line describes two nodes that are connected. Examples: Input: Outp
11 min read
Maximum sum of leaf nodes among all levels of the given binary tree
Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum of leaf nodes among all level of the given binary tree.Examples: Input: 4 / \ 2 -5 / \ -1 3 Output: 2 Sum of all leaves at 0th level is 0. Sum of all leaves at 1st level is -5. Sum of all leaves at 2nd level is 2. Hence maximum sum is 2. Input: 1 / \ 2 3 / \
9 min read
Maximum sum of non-leaf nodes among all levels of the given binary tree
Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum of non-leaf nodes among all levels of the given binary tree. Examples: Input: 4 / \ 2 -5 / \ -1 3 Output: 4 Sum of all non-leaf nodes at 0th level is 4. Sum of all non-leaf nodes at 1st level is 2. Sum of all non-leaf nodes at 2nd level is 0. Hence maximum s
9 min read
Sum of nodes at maximum depth of a Binary Tree
Given a root node to a tree, find the sum of all the leaf nodes which are at maximum depth from root node. Example: 1 / \ 2 3 / \ / \ 4 5 6 7 Input : root(of above tree) Output : 22 Explanation: Nodes at maximum depth are: 4, 5, 6, 7. So, sum of these nodes = 22 While traversing the nodes compare the level of the node with max_level (Maximum level
15+ min read
Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
Given a root node to a tree, find the sum of all the leaf nodes which are at maximum depth from the root node. Example: 1 / \ 2 3 / \ / \ 4 5 6 7Input : root(of above tree)Output : 22Explanation:Nodes at maximum depth are 4, 5, 6, 7. So, the sum of these nodes = 22Approach: There exists a recursive approach to this problem. This can also be solved
8 min read
Count of nodes in a binary tree having their nodes in range [L, R]
Given a Binary Tree consisting of N nodes and two positive integers L and R, the task is to find the count of nodes having their value in the range [L, R]. Examples: Input: Tree in the image below, L = 4, R = 15 Output: 2Explanation: The nodes in the given Tree that lies in the range [4, 15] are {5, 10}. Input: Tree in the image below, L = 8, R = 2
11 min read
Check if all nodes of the Binary Tree can be represented as sum of two primes
Given a binary tree of N nodes with odd value. The task is to check whether all the nodes of the tree can be represented as the sum of the two prime numbers or not. Examples: Input: Output: Yes Explanation: All the nodes in the tree can be represented as the sum of two prime numbers as: 9 = 2 + 7 15 = 2 +13 7 = 2 + 5 19 = 2 + 17 25 = 2 + 23 13 = 11
11 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Convert a Binary Tree into its Mirror Tree (Invert Binary Tree)
Given a binary tree, the task is to convert the binary tree into its Mirror tree. Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. Recommended PracticeMirror TreeTry It!The idea is to traverse recursively and swap the right and left subtrees after traversing the subtrees. Follow
15+ min read
Common nodes in the inorder sequence of a tree between given two nodes in O(1) space
Given a binary tree consisting of distinct values and two numbers K1 and K2, the task is to find all nodes that lie between them in the inorder sequence of the tree. Examples: Input: 1 / \ 12 11 / / \ 3 4 13 \ / 15 9 k1 = 12 k2 = 15 Output: 1 4 Explanation: Inorder sequence is 3 12 1 4 15 11 9 13 The common nodes between 12 and 15 in the inorder se
10 min read
Sum of Bitwise AND of the sum of all leaf and non-leaf nodes for each level of a Binary Tree
Given a Binary Tree consisting of N nodes, the task is to find the sum of Bitwise AND of the sum of all leaf nodes and the sum of all non-leaf nodes for each level in the given Tree. Examples: Input: Below is the given tree: 5 / \ 3 9 / \ 6 4 \ 7Output: 5Explanation: For Level 1: leaf node sum = 0, non-leaf node sum = 5. So, 0&amp;5 = 0. For Level
10 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg