Node with maximum child sum
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.
The first and only line of output contains the data of the node with maximum sum, as described in the task.
Time Limit: 1 sec
5 3 1 2 3 1 15 2 4 5 1 6 0 0 0 0
1
/************************************************************
Following is the structure for the TreeNode class
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]; } } };
************************************************************/
void maxSum(TreeNode<int> *root, TreeNode<int> **maxNode, int *max) { int sum = root->data; for (int i = 0; i < root->children.size(); i++) sum += root->children[i]->data; if (sum > *max) { *max = sum; *maxNode = root; } for (int i = 0; i < root->children.size(); i++) maxSum(root->children[i], maxNode, max);}
TreeNode<int> *maxSumNode(TreeNode<int> *root) { // Write your code here if (root == NULL) { return NULL; } TreeNode<int> *maxNode; int max = 0; maxSum(root, &maxNode, &max); return maxNode;}
Comments
Post a Comment