Number of children of given node in n-ary Tree

23 Jun, 2021
Given a node x, find the number of children of x(if it exists) in the given n-ary tree.  
Example :  
Input : x = 50
Output : 3
Explanation : 50 has 3 children having values 40, 100 and 20.
 
Approach :  
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.
Initialize the number of children as 0.
For every node in the n-ary tree, check if its value is equal to x or not. If yes, then return the number of children.
If the value of x is not equal to the current node then, push all the children of current node in the queue.
Keep Repeating the above step until the queue becomes empty.
Below is the implementation of the above idea :  
C++
Java
Python3
C#
Javascript
// C++ program to find number// of children of given node#include <bits/stdc++.h>using namespace std; // Represents a node of an n-ary treeclass Node { public:    int key;    vector<Node*> child;     Node(int data)    {        key = data;    }}; // Function to calculate number// of children of given nodeint numberOfChildren(Node* root, int x){    // initialize the numChildren as 0    int numChildren = 0;     if (root == NULL)        return 0;     // Creating a queue and pushing the root    queue<Node*> q;    q.push(root);     while (!q.empty()) {        int n = q.size();         // If this node has children        while (n > 0) {             // Dequeue an item from queue and            // check if it is equal to x            // If YES, then return number of children            Node* p = q.front();            q.pop();            if (p->key == x) {                numChildren = numChildren + p->child.size();                return numChildren;            }             // Enqueue all children of the dequeued item            for (int i = 0; i < p->child.size(); i++)                q.push(p->child[i]);            n--;        }    }    return numChildren;} // Driver programint main(){    // Creating a generic tree    Node* root = new Node(20);    (root->child).push_back(new Node(2));    (root->child).push_back(new Node(34));    (root->child).push_back(new Node(50));    (root->child).push_back(new Node(60));    (root->child).push_back(new Node(70));    (root->child[0]->child).push_back(new Node(15));    (root->child[0]->child).push_back(new Node(20));    (root->child[1]->child).push_back(new Node(30));    (root->child[2]->child).push_back(new Node(40));    (root->child[2]->child).push_back(new Node(100));    (root->child[2]->child).push_back(new Node(20));    (root->child[0]->child[1]->child).push_back(new Node(25));    (root->child[0]->child[1]->child).push_back(new Node(50));     // Node whose number of    // children is to be calculated    int x = 50;     // Function calling    cout << numberOfChildren(root, x) << endl;     return 0;}
// Java program to find number// of children of given nodeimport java.util.*; class GFG{ // Represents a node of an n-ary treestatic class Node{    int key;    Vector<Node> child = new Vector<>();     Node(int data)    {        key = data;    }}; // Function to calculate number// of children of given nodestatic int numberOfChildren(Node root, int x){    // initialize the numChildren as 0    int numChildren = 0;     if (root == null)        return 0;     // Creating a queue and pushing the root    Queue<Node> q = new LinkedList<Node>();    q.add(root);     while (!q.isEmpty())    {        int n = q.size();         // If this node has children        while (n > 0)        {             // Dequeue an item from queue and            // check if it is equal to x            // If YES, then return number of children            Node p = q.peek();            q.remove();            if (p.key == x)            {                numChildren = numChildren +                              p.child.size();                return numChildren;            }             // Enqueue all children of the dequeued item            for (int i = 0; i < p.child.size(); i++)                q.add(p.child.get(i));            n--;        }    }    return numChildren;} // Driver Codepublic static void main(String[] args){         // Creating a generic tree    Node root = new Node(20);    (root.child).add(new Node(2));    (root.child).add(new Node(34));    (root.child).add(new Node(50));    (root.child).add(new Node(60));    (root.child).add(new Node(70));    (root.child.get(0).child).add(new Node(15));    (root.child.get(0).child).add(new Node(20));    (root.child.get(1).child).add(new Node(30));    (root.child.get(2).child).add(new Node(40));    (root.child.get(2).child).add(new Node(100));    (root.child.get(2).child).add(new Node(20));    (root.child.get(0).child.get(1).child).add(new Node(25));    (root.child.get(0).child.get(1).child).add(new Node(50));     // Node whose number of    // children is to be calculated    int x = 50;     // Function calling    System.out.println(numberOfChildren(root, x));}} // This code is contributed by 29AjayKumar
# Python3 program to find number# of children of given node # Node of a linked listclass Node:    def __init__(self, data = None):        self.key = data        self.child = [] # Function to calculate number# of children of given nodedef numberOfChildren( root, x):     # initialize the numChildren as 0    numChildren = 0     if (root == None):        return 0     # Creating a queue and appending the root    q = []    q.append(root)     while (len(q) > 0) :        n = len(q)         # If this node has children        while (n > 0):             # Dequeue an item from queue and            # check if it is equal to x            # If YES, then return number of children            p = q[0]            q.pop(0)            if (p.key == x) :                numChildren = numChildren + len(p.child)                return numChildren                         i = 0                         # Enqueue all children of the dequeued item            while ( i < len(p.child)):                q.append(p.child[i])                i = i + 1            n = n - 1     return numChildren # Driver program # Creating a generic treeroot = Node(20)(root.child).append(Node(2))(root.child).append(Node(34))(root.child).append(Node(50))(root.child).append(Node(60))(root.child).append(Node(70))(root.child[0].child).append(Node(15))(root.child[0].child).append(Node(20))(root.child[1].child).append(Node(30))(root.child[2].child).append(Node(40))(root.child[2].child).append(Node(100))(root.child[2].child).append(Node(20))(root.child[0].child[1].child).append(Node(25))(root.child[0].child[1].child).append(Node(50)) # Node whose number of# children is to be calculatedx = 50 # Function callingprint( numberOfChildren(root, x) ) # This code is contributed by Arnab Kundu
// C# program to find number// of children of given nodeusing System;using System.Collections.Generic;     class GFG{ // Represents a node of an n-ary treepublic class Node{    public int key;    public List<Node> child = new List<Node>();     public Node(int data)    {        key = data;    }}; // Function to calculate number// of children of given nodestatic int numberOfChildren(Node root, int x){    // initialize the numChildren as 0    int numChildren = 0;     if (root == null)        return 0;     // Creating a queue and pushing the root    Queue<Node> q = new Queue<Node>();    q.Enqueue(root);     while (q.Count != 0)    {        int n = q.Count;         // If this node has children        while (n > 0)        {             // Dequeue an item from queue and            // check if it is equal to x            // If YES, then return number of children            Node p = q.Peek();            q.Dequeue();            if (p.key == x)            {                numChildren = numChildren +                              p.child.Count;                return numChildren;            }             // Enqueue all children of the dequeued item            for (int i = 0; i < p.child.Count; i++)                q.Enqueue(p.child[i]);            n--;        }    }    return numChildren;} // Driver Codepublic static void Main(String[] args){         // Creating a generic tree    Node root = new Node(20);    (root.child).Add(new Node(2));    (root.child).Add(new Node(34));    (root.child).Add(new Node(50));    (root.child).Add(new Node(60));    (root.child).Add(new Node(70));    (root.child[0].child).Add(new Node(15));    (root.child[0].child).Add(new Node(20));    (root.child[1].child).Add(new Node(30));    (root.child[2].child).Add(new Node(40));    (root.child[2].child).Add(new Node(100));    (root.child[2].child).Add(new Node(20));    (root.child[0].child[1].child).Add(new Node(25));    (root.child[0].child[1].child).Add(new Node(50));     // Node whose number of    // children is to be calculated    int x = 50;     // Function calling    Console.WriteLine(numberOfChildren(root, x));}} // This code is contributed by 29AjayKumar
<script> // javascript program to find number// of children of given node // Represents a node of an n-ary treeclass Node{    constructor(data)    {        this.key = data;        this.child = []    }}; // Function to calculate number// of children of given nodefunction numberOfChildren(root, x){    // initialize the numChildren as 0    var numChildren = 0;     if (root == null)        return 0;     // Creating a queue and pushing the root    var q = [];    q.push(root);     while (q.length != 0)    {        var n = q.length;         // If this node has children        while (n > 0)        {             // Dequeue an item from queue and            // check if it is equal to x            // If YES, then return number of children            var p = q[0];            q.shift();            if (p.key == x)            {                numChildren = numChildren +                              p.child.length;                return numChildren;            }             // push all children of the dequeued item            for (var i = 0; i < p.child.length; i++)                q.push(p.child[i]);            n--;        }    }    return numChildren;} // Driver Code// Creating a generic treevar root = new Node(20);(root.child).push(new Node(2));(root.child).push(new Node(34));(root.child).push(new Node(50));(root.child).push(new Node(60));(root.child).push(new Node(70));(root.child[0].child).push(new Node(15));(root.child[0].child).push(new Node(20));(root.child[1].child).push(new Node(30));(root.child[2].child).push(new Node(40));(root.child[2].child).push(new Node(100));(root.child[2].child).push(new Node(20));(root.child[0].child[1].child).push(new Node(25));(root.child[0].child[1].child).push(new Node(50)); // Node whose number of// children is to be calculatedvar x = 50; // Function callingdocument.write(numberOfChildren(root, x)); // This code is contributed by itsok.</script>
3
 
Time Complexity : O(N), where N is the number of nodes in tree. Auxiliary Space : O(N), where N is the number of nodes in tree.  
Number of children of given node in n-ary Tree | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersNumber of children of given node in n-ary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You'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.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:35•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=TPTa3cm5YYc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk 
29AjayKumar
andrew1234
itsok
n-ary-tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Print Right View of a Binary Tree
BFS vs DFS for Binary Tree
Introduction to Data Structures
Introduction to Tree Data Structure
A program to check if a binary tree is BST or not
Binary Tree | Set 3 (Types of Binary Tree)
Decision Tree
Binary Tree | Set 2 (Properties)
Iterative Preorder Traversal
What is Data Structure: Types, Classifications and Applications