[Geeks for Geeks] Maximum sum of Non-adjacent nodes

Maximum sum of Non-adjacent nodes

Given a binary tree with a value associated with each node, we need 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 or parents in consideration and vice versa.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution{
pair<int, int> helper(Node* node) {
if(!node) return {0, 0};
auto l = helper(node->left);
auto r = helper(node->right);

auto adj = l.second + r.second + node->data;
auto nonadj = r.first + l.first;
return {adj, max({r.first + l.first, r.first + l.second, r.second + l.first, r.second + l.second})};
}
public:
//Function to return the maximum sum of non-adjacent nodes.
int getMaxSum(Node *root)
{
auto res = helper(root);
return max(res.first, res.second);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/25/PS/GeeksforGeeks/maximum-sum-of-non-adjacent-nodes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.