Node having maximum sum of immediate children and itself in n-ary tree

28 Jun, 2021
Given an N-Ary tree, find and return the node for which sum of data of all children and the node itself is maximum. In the sum, data of node itself and data of its immediate children is to be taken. For example in the given tree, 
 
maxSum Node = 4 with maximum sum of 28
 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
The idea is we will maintain a integer variable maxsum which contains the maximum sum yet, and a resnode node pointer which points to the node with maximum sum. Traverse the tree and maintain the sum of root and data of all its immediate children in currsum integer variable and update the maxsum variable accordingly.  
C++
Java
Python3
C#
Javascript
// CPP program to find the node whose children// and node sum is maximum.#include <bits/stdc++.h>using namespace std; // Structure of a node of an n-ary treestruct Node {    int key;    vector<Node*> child;}; // Utility function to create a new tree nodeNode* newNode(int key){    Node* temp = new Node;    temp->key = key;    return temp;} // Helper function to find the nodevoid maxSumUtil(Node* root, Node** resNode,                int* maxsum){    // Base Case    if (root == NULL)        return;     // curr contains the sum of the root and    // its children    int currsum = root->key;     // total no of children    int count = root->child.size();     // for every child call recursively    for (int i = 0; i < count; i++) {        currsum += root->child[i]->key;        maxSumUtil(root->child[i], resNode, maxsum);    }     // if curr is greater than sum, update it    if (currsum > *maxsum) {         // resultant node        *resNode = root;        *maxsum = currsum;    }    return;} // Function to find the node having max sum of// children and nodeint maxSum(Node* root){    // resultant node with max sum of children    // and node    Node* resNode;     // sum of node and its children    int maxsum = 0;     maxSumUtil(root, &resNode, &maxsum);     // return the key of resultant node    return resNode->key;} // Driver programint main(){    /*   Let us create below tree    *              1    *          /   |  \    *         2   3   4    *        / \    / |  \ \    *       5   6  7  8  9  10    */     Node* root = newNode(1);    (root->child).push_back(newNode(2));    (root->child).push_back(newNode(3));    (root->child).push_back(newNode(4));    (root->child[0]->child).push_back(newNode(5));    (root->child[0]->child).push_back(newNode(6));    (root->child[2]->child).push_back(newNode(5));    (root->child[2]->child).push_back(newNode(6));    (root->child[2]->child).push_back(newNode(6));     cout << maxSum(root) << endl;     return 0;}
// Java program to find the node whose children// and node sum is maximum.import java.util.*; class GFG{     // Structure of a node of an n-ary treestatic class Node{    int key;    Vector<Node> child;    Node()    {        child = new Vector<Node>();    }}; // Utility function to create a new tree nodestatic Node newNode(int key){    Node temp = new Node();    temp.key = key;    return temp;} static int maxsum; // resultant node with max sum of children// and nodestatic Node resNode; // Helper function to find the nodestatic void maxSumUtil(Node root){    // Base Case    if (root == null)        return;     // curr contains the sum of the root and    // its children    int currsum = root.key;     // total no of children    int count = root.child.size();     // for every child call recursively    for (int i = 0; i < count; i++)    {        currsum += root.child.get(i).key;        maxSumUtil(root.child.get(i));    }     // if curr is greater than sum, update it    if (currsum > maxsum)    {         // resultant node        resNode = root;        maxsum = currsum;    }    return;} // Function to find the node having max sum of// children and nodestatic int maxSum(Node root){         // sum of node and its children    int maxsum = 0;     maxSumUtil(root);     // return the key of resultant node    return resNode.key;} // Driver codepublic static void main(String args[]){    /* Let us create below tree                1            / | \            2 3 4        / \ / | \ \        5 6 7 8 9 10    */     Node root = newNode(1);    (root.child).add(newNode(2));    (root.child).add(newNode(3));    (root.child).add(newNode(4));    (root.child.get(0).child).add(newNode(5));    (root.child.get(0).child).add(newNode(6));    (root.child.get(2).child).add(newNode(5));    (root.child.get(2).child).add(newNode(6));    (root.child.get(2).child).add(newNode(6));     System.out.print( maxSum(root) );}} // This code is contributed by Arnab Kundu
# Python3 program to find the node# whose children and node sum is maximum. # Structure of a node of an n-ary treeclass Node:         def __init__(self, key):        self.key = key        self.child = [] # Helper function to find the nodedef maxSumUtil(root, resNode, maxsum):     # Base Case    if root == None:        return     # curr contains the sum of the root    # and its children    currsum = root.key     # total no of children    count = len(root.child)     # for every child call recursively    for i in range(0, count):        currsum += root.child[i].key        resNode, maxsum = maxSumUtil(root.child[i],                                     resNode, maxsum)     # if curr is greater than sum,    # update it    if currsum > maxsum:         # resultant node        resNode = root        maxsum = currsum         return resNode, maxsum # Function to find the node having# max sum of children and nodedef maxSum(root):     # resultant node with max    # sum of children and node    resNode, maxsum = Node(None), 0    resNode, maxsum = maxSumUtil(root, resNode,                                       maxsum)     # return the key of resultant node    return resNode.key # Driver Codeif __name__ == "__main__":     root = Node(1)    (root.child).append(Node(2))    (root.child).append(Node(3))    (root.child).append(Node(4))    (root.child[0].child).append(Node(5))    (root.child[0].child).append(Node(6))    (root.child[2].child).append(Node(5))    (root.child[2].child).append(Node(6))    (root.child[2].child).append(Node(6))     print(maxSum(root)) # This code is contributed by Rituraj Jain
// C# program to find the node whose children// and node sum is maximumusing System;using System.Collections.Generic; class GFG{     // Structure of a node of an n-ary treepublic class Node{    public int key;    public List<Node> child;    public Node()    {        child = new List<Node>();    }}; // Utility function to create a new tree nodestatic Node newNode(int key){    Node temp = new Node();    temp.key = key;    return temp;} static int maxsum; // resultant node with max sum of children// and nodestatic Node resNode; // Helper function to find the nodestatic void maxSumUtil(Node root){    // Base Case    if (root == null)        return;     // curr contains the sum of the root and    // its children    int currsum = root.key;     // total no of children    int count = root.child.Count;     // for every child call recursively    for (int i = 0; i < count; i++)    {        currsum += root.child[i].key;        maxSumUtil(root.child[i]);    }     // if curr is greater than sum, update it    if (currsum > maxsum)    {         // resultant node        resNode = root;        maxsum = currsum;    }    return;} // Function to find the node having max sum of// children and nodestatic int maxSum(Node root){         // sum of node and its children    int maxsum = 0;     maxSumUtil(root);     // return the key of resultant node    return resNode.key;} // Driver codepublic static void Main(String []args){    /* Let us create below tree                1            / | \            2 3 4        / \ / | \ \        5 6 7 8 9 10    */     Node root = newNode(1);    (root.child).Add(newNode(2));    (root.child).Add(newNode(3));    (root.child).Add(newNode(4));    (root.child[0].child).Add(newNode(5));    (root.child[0].child).Add(newNode(6));    (root.child[2].child).Add(newNode(5));    (root.child[2].child).Add(newNode(6));    (root.child[2].child).Add(newNode(6));     Console.Write( maxSum(root) );}} // This code has been contributed by 29AjayKumar
<script> // JavaScript program to find the node whose children// and node sum is maximum      // Structure of a node of an n-ary treeclass Node{    constructor()    {        this.key = null;        this.child = []    }}; // Utility function to create a new tree nodefunction newNode(key){    var temp = new Node();    temp.key = key;    return temp;} var maxsum = 0; // resultant node with max sum of children// and nodevar resNode = 0; // Helper function to find the nodefunction maxSumUtil(root){    // Base Case    if (root == null)        return;     // curr contains the sum of the root and    // its children    var currsum = root.key;     // total no of children    var count = root.child.length;     // for every child call recursively    for (var i = 0; i < count; i++)    {        currsum += root.child[i].key;        maxSumUtil(root.child[i]);    }     // if curr is greater than sum, update it    if (currsum > maxsum)    {         // resultant node        resNode = root;        maxsum = currsum;    }    return;} // Function to find the node having max sum of// children and nodefunction maxSum(root){         // sum of node and its children    var maxsum = 0;     maxSumUtil(root);     // return the key of resultant node    return resNode.key;} // Driver code/* Let us create below tree            1        / | \        2 3 4    / \ / | \ \    5 6 7 8 9 10*/var root = newNode(1);(root.child).push(newNode(2));(root.child).push(newNode(3));(root.child).push(newNode(4));(root.child[0].child).push(newNode(5));(root.child[0].child).push(newNode(6));(root.child[2].child).push(newNode(5));(root.child[2].child).push(newNode(6));(root.child[2].child).push(newNode(6));document.write( maxSum(root) ); </script>
Output:  
4
 
Node having maximum sum of immediate children and itself in n-ary tree | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersNode having maximum sum of immediate children and itself in n-ary tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:11•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=bo3IUFopia8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Chhavi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
rituraj_jain
andrew1234
29AjayKumar
rrrtnx
n-ary-tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Introduction to Tree Data Structure
What is Data Structure: Types, Classifications and Applications
Binary Tree | Set 3 (Types of Binary Tree)
A program to check if a binary tree is BST or not
Binary Tree | Set 2 (Properties)
Diameter of a Binary Tree
Lowest Common Ancestor in a Binary Tree | Set 1
Decision Tree
Diagonal Traversal of Binary Tree