« Node with maximum child sum iteratively

Node with maximum child sum

Given a generic tree, find and return the node for which sum of its data and data of all its child nodes is maximum. In the sum, data of the node and data of its immediate child nodes has to be taken.

Input format :

The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space.

Output format :

The first and only line of output contains the data of the node with maximum sum, as described in the task.

Constraints:

Time Limit: 1 sec

Sample Input 1 :

5 3 1 2 3 1 15 2 4 5 1 6 0 0 0 0

Sample Output 1 :

1

1#include <iostream>
2#include <queue>
3#include <vector>
4#include<climits>
5using namespace std;
6
7template <typename T>
8class TreeNode {
9 public:
10 T data;
11 vector<TreeNode<T>*> children;
12
13 TreeNode(T data) { this->data = data; }
14
15 ~TreeNode() {
16 for (int i = 0; i < children.size(); i++) {
17 delete children[i];
18 }
19 }
20};
21
22TreeNode<int>* maxSumNode(TreeNode<int>* root) {
23 // Write your code here
24 if(root == NULL){
25 return NULL;
26 }
27
28 queue<TreeNode<int>*> q;
29 q.push(root);
30 TreeNode<int>* ansNode = NULL;
31 int ans = INT_MIN;
32 while(!q.empty()){
33 TreeNode<int>* top = q.front();
34 q.pop();
35 int currSum = top->data;
36 for(int i=0; i<top->children.size(); i++){
37 currSum = currSum + top->children[i]->data;
38 q.push(top->children[i]);
39 }
40
41 if(ans < currSum){
42 ans = currSum;
43 ansNode = top;
44 }
45 }
46
47 return ansNode;
48}
49
50TreeNode<int>* takeInputLevelWise() {
51 int rootData;
52 cin >> rootData;
53 TreeNode<int>* root = new TreeNode<int>(rootData);
54
55 queue<TreeNode<int>*> pendingNodes;
56
57 pendingNodes.push(root);
58 while (pendingNodes.size() != 0) {
59 TreeNode<int>* front = pendingNodes.front();
60 pendingNodes.pop();
61 int numChild;
62 cin >> numChild;
63 for (int i = 0; i < numChild; i++) {
64 int childData;
65 cin >> childData;
66 TreeNode<int>* child = new TreeNode<int>(childData);
67 front->children.push_back(child);
68 pendingNodes.push(child);
69 }
70 }
71
72 return root;
73}
74
75int main() {
76 TreeNode<int>* root = takeInputLevelWise();
77
78 TreeNode<int>* ans = maxSumNode(root);
79
80 if (ans != NULL) {
81 cout << ans->data;
82 }
83}