Maximum sum of Non-adjacent nodes

Can you please tellme the error in this method which i choose
Code:-
int getSum(vector vect){
int n=vect.size(); int i,excl=0,incl=vect[0],excl_new; for(i=1;i<n;i++){
excl_new=max(incl,excl); incl=excl+vect[i]; excl=excl_new; }
return max(incl,excl);
}
int getMaxSum(Node *root) {
vector vect;
if(root==NULL){
return 0;
}
getMaxSum(root->left);
vect.push_back(root->data); getMaxSum(root->right);
return getSum(vect); }

hello @manikjindal49
pls share ur code using cb ide.
also share the problem link

ide:-https://ide.codingblocks.com/s/353165

Question :-Maximum sum of nonadjacent nodes Geeks for geeks practice

no the logic is incorrect.

u cannot convert ur tree into linear array and the look to non adjacent node (this will not enure that included elements r non adjacent ).

hint ->
a)try to do it using recursion
b) return pair from node (which contains these two information -> answer when included current ,answer when excluded current node)

but why we cannot our tree to rray please give me more more explanation on that with anyexample you have

Hey @manikjindal49
Here for this : 11 1 2 20 30 N N

. . …11
…1 . . …2
20 .30 N N

Here output should be 61 but urs is giving 11 ,first thing it will not flatten, because each recursive call is making a vector of its own
Even if it flattens it will become 20 1 30 11 2 Here u will not be able to pick both 11 & 30

Here is the logic for the same
Return a pair for each node in the binary tree such that first of the pair indicates maximum sum when the data of node is included and second indicates maximum sum when the data of a particular node is not included.

ok thank you i understand that but now i am facing problem in this Alyona and strings Actually i am not able to understand the concept of this question like what they want can you please explain me this question also

1 Like

Hey please open another doubt for the same.:slight_smile: