Skip to content

Commit 08cd626

Browse files
authored
Create main.cpp
1 parent b73c0f2 commit 08cd626

File tree

1 file changed

+28
-0
lines changed
  • 17 - Binary Tree Data Structure Problems/29 - Maximum Sum of Non-adjacent Nodes

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution{
2+
public:
3+
pair<int, int> solve(Node* root){
4+
if(root == NULL) {
5+
pair<int, int> p = make_pair(0, 0);
6+
return p;
7+
};
8+
9+
10+
pair<int, int> left = solve(root -> left);
11+
pair<int, int> right = solve(root -> right);
12+
13+
pair<int, int> res;
14+
res.first = root -> data + left.second + right.second;
15+
res.second = max(left.first, left.second) + max(right.first, right.second);
16+
17+
18+
return res;
19+
20+
}
21+
//Function to return the maximum sum of non-adjacent nodes.
22+
int getMaxSum(Node *root)
23+
{
24+
pair<int, int> ans = solve(root);
25+
return max(ans.first, ans.second);
26+
27+
}
28+
};

0 commit comments

Comments
 (0)