-
Notifications
You must be signed in to change notification settings - Fork 113
/
MaxSumFromAnyNodetoAnyNode.cpp
79 lines (62 loc) · 1.21 KB
/
MaxSumFromAnyNodetoAnyNode.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include<bits/stdc++.h>
using namespace std;
///for trees
#include<bits/stdc++.h>
using namespace std;
class node{
public:
node* left;
node* right;
int data;
node(int d)
{
left=NULL;
right=NULL;
data=d;
}
};
class pairr{
public:
int branchsum;
int maxsum;
pairr(){
branchsum=0;
maxsum=0;
}
};
pairr MaxSumPath(node* root)
{
pairr p;
if(root==NULL)
{
return p;
}
pairr left = MaxSumPath(root->left);
pairr right = MaxSumPath(root->right);
//construct two values
int op1 = root->data;
int op2 = left.branchsum + root->data;
int op3 = left.branchsum + right.branchsum + root->data;
int op4 = right.branchsum + root->data;
int curr_ans_through_root = max(op1,op2,op3,op4);
//BRANCH SUM
t.branchsum = (max(left.branchsum,right,branchsum,0))+root->data;
p.maxsum = max(left.maxsum,right.maxsum,curr_ans_through_root);
}
node* buildtree(){
int d;
cin>>d;
if(d==-1)
{
return NULL;
}
node* root = new node(d);
root->left = buildtree();
root->right=buildtree();
return root;
}
int main()
{
node* root=buildtree();
return 0;
}