-
Notifications
You must be signed in to change notification settings - Fork 51
/
Tree_max_child_sum.cpp
75 lines (63 loc) · 1.67 KB
/
Tree_max_child_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
75
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
template <typename T>
class TreeNode {
public:
T data;
vector<TreeNode<T>*> children;
TreeNode(T data) { this->data = data; }
~TreeNode() {
for (int i = 0; i < children.size(); i++) {
delete children[i];
}
}
};
TreeNode<int>* maxSumNode(TreeNode<int>* root) {
if(root==NULL)
{
return NULL;
}
TreeNode<int> *result = root; // root node
int max = root->data; // root node
int childCount = root->children.size();
for(int i=0; i<childCount; i++)
{
TreeNode<int> *temp = maxSumNode(root->children[i]);
if(temp->data > max)
{
max = temp->data;
result = temp;
}
}
return result;
}
TreeNode<int>* takeInputLevelWise() {
int rootData;
cin >> rootData;
TreeNode<int>* root = new TreeNode<int>(rootData);
queue<TreeNode<int>*> pendingNodes;
pendingNodes.push(root);
while (pendingNodes.size() != 0) {
TreeNode<int>* front = pendingNodes.front();
pendingNodes.pop();
int numChild;
cin >> numChild;
for (int i = 0; i < numChild; i++) {
int childData;
cin >> childData;
TreeNode<int>* child = new TreeNode<int>(childData);
front->children.push_back(child);
pendingNodes.push(child);
}
}
return root;
}
int main() {
TreeNode<int>* root = takeInputLevelWise();
TreeNode<int>* ans = maxSumNode(root);
if (ans != NULL) {
cout << ans->data;
}
}