-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlargest_subtree_sum.cpp
74 lines (61 loc) · 1.33 KB
/
largest_subtree_sum.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
//Given a binary tree, task is to find subtree with maximum sum in tree.
#include <bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node *left;
node *right;
node(int x){
data = x;
left = NULL;
right = NULL;
}
};
node *buildTree(string s){
if(s.length() == 0 || s[0] == 'N') return NULL;
vector<string> ip;
istringstream iss(s);
for(string s; iss >> s;) ip.push_back(s);
node *root = new node(stoi(ip[0]));
queue<node *> queue;
queue.push(root);
int i = 1;
while(!queue.empty() && i < ip.size()){
node *cur = queue.front();
queue.pop();
string currval = ip[i];
if(currval != "N"){
cur->left = new node(stoi(currval));
queue.push(cur->left);
}
i++;
if(i >= ip.size()) break;
currval = ip[i];
if(currval != "N"){
cur->right = new node(stoi(currval));
queue.push(cur->left);
}
i++;
}
return root;
}
int LargestSubtreeSumUtil(node *root, int &res){
if(root == NULL) return 0;
int cursum = root->data+LargestSubtreeSumUtil(root->left, res)+LargestSubtreeSumUtil(root->right,res);
res = max(res,cursum);
return cursum;
}
int LargestSubtreeSum(node *root){
if(root == NULL) return 0;
int res = INT_MIN;
int cur = LargestSubtreeSumUtil(root, res);
return res;
}
int main(){
string s;
getline(cin,s);
node *root = buildTree(s);
cout << LargestSubtreeSum(root);
return 0;
}