Skip to content

Commit c87b6e1

Browse files
authored
Create 15. Node with maximum child sum.cpp
1 parent 5fcf568 commit c87b6e1

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/************************************************************
2+
3+
Following is the structure for the TreeNode class
4+
5+
template <typename T>
6+
class TreeNode {
7+
public:
8+
T data;
9+
vector<TreeNode<T>*> children;
10+
11+
TreeNode(T data) {
12+
this->data = data;
13+
}
14+
15+
~TreeNode() {
16+
for (int i = 0; i < children.size(); i++) {
17+
delete children[i];
18+
}
19+
}
20+
};
21+
22+
************************************************************/
23+
24+
TreeNode<int>* maxSumNode(TreeNode<int>* root) {
25+
// Write your code here
26+
TreeNode<int>* ans = root;
27+
int sum = root->data;
28+
for(int i=0;i<root->children.size();i++){
29+
sum+=root->children[i]->data;
30+
}
31+
for(int i=0;i<root->children.size();i++){
32+
TreeNode<int>* x = maxSumNode(root->children[i]);
33+
int xsum = x->data;
34+
for(int k=0;k<x->children.size();k++){
35+
xsum+=x->children[k]->data;
36+
}
37+
if(xsum>sum){
38+
ans = x;
39+
}
40+
}
41+
return ans;
42+
43+
}

0 commit comments

Comments
 (0)