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

In this tutorial, we will be discussing a program to find maximum sum of nodes in Binary tree such that no two are adjacent using Dynamic Programming.

For this we will be provided with a binary tree. Our task is to find the subset having maximum sum such that no two nodes in the subset are directly connected using Dynamic Programming.

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
//finding diameter using dynamic programming
void dfs(int node, int parent, int dp1[], int dp2[], list<int>* adj, int tree[]){
int sum1 = 0, sum2 = 0;
++i) {
if (*i == parent)
continue;
dfs(*i, node, dp1, dp2, adj, tree);
sum1 += dp2[*i];
sum2 += max(dp1[*i], dp2[*i]);
}
dp1[node] = tree[node] + sum1;
dp2[node] = sum2;
}
int main() {
int n = 5;
list<int>* adj = new list<int>[n + 1];
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);
cout << "Maximum sum: " << max(dp1[1], dp2[1]) << endl;
return 0;
}

Output

Maximum sum: 25

Updated on: 09-Sep-2020

53 Views