We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent b73c0f2 commit 08cd626Copy full SHA for 08cd626
17 - Binary Tree Data Structure Problems/29 - Maximum Sum of Non-adjacent Nodes/main.cpp
@@ -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