Number of siblings of a given Node in n-ary Tree - GeeksforGeeks

24 Jun, 2021
Given an N-ary tree, find the number of siblings of given node x. Assume that x exists in the given n-ary tree. 
Example :  
Input : 30
Output : 3
 
Approach: For every node in the given n-ary tree, push the children of the current node in the queue. While adding the children of current node in queue, check if any children is equal to the given value x or not. If yes, then return the number of siblings of x. Below is the implementation of the above idea :  
C++
Java
Python3
C#
Javascript
// C++ program to find number// of siblings of a 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 siblings of a given nodeint numberOfSiblings(Node* root, int x){    if (root == NULL)        return 0;     // Creating a queue and    // pushing the root    queue<Node*> q;    q.push(root);     while (!q.empty()) {        // 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();         // Enqueue all children of        // the dequeued item        for (int i = 0; i < p->child.size(); i++) {            // If the value of children            // is equal to x, then return            // the number of siblings            if (p->child[i]->key == x)                return p->child.size() - 1;            q.push(p->child[i]);        }    }} // Driver programint main(){    // Creating a generic tree as shown in above figure    Node* root = new Node(50);    (root->child).push_back(new Node(2));    (root->child).push_back(new Node(30));    (root->child).push_back(new Node(14));    (root->child).push_back(new Node(60));    (root->child[0]->child).push_back(new Node(15));    (root->child[0]->child).push_back(new Node(25));    (root->child[0]->child[1]->child).push_back(new Node(70));    (root->child[0]->child[1]->child).push_back(new Node(100));    (root->child[1]->child).push_back(new Node(6));    (root->child[1]->child).push_back(new Node(1));    (root->child[2]->child).push_back(new Node(7));    (root->child[2]->child[0]->child).push_back(new Node(17));    (root->child[2]->child[0]->child).push_back(new Node(99));    (root->child[2]->child[0]->child).push_back(new Node(27));    (root->child[3]->child).push_back(new Node(16));     // Node whose number of    // siblings is to be calculated    int x = 100;     // Function calling    cout << numberOfSiblings(root, x) << endl;     return 0;}
// Java program to find number// of siblings of a given nodeimport java.util.*; class GFG{     // Represents a node of an n-ary treestatic class Node{    int key;    Vector<Node> child;     Node(int data)    {        key = data;        child = new Vector<Node>();    }}; // Function to calculate number// of siblings of a given nodestatic int numberOfSiblings(Node root, int x){    if (root == null)        return 0;     // Creating a queue and    // pushing the root    Queue<Node> q = new LinkedList<>();    q.add(root);     while (q.size() > 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();         // Enqueue all children of        // the dequeued item        for (int i = 0; i < p.child.size(); i++)        {            // If the value of children            // is equal to x, then return            // the number of siblings            if (p.child.get(i).key == x)                return p.child.size() - 1;            q.add(p.child.get(i));        }    }    return -1;} // Driver codepublic static void main(String args[]){    // Creating a generic tree as shown in above figure    Node root = new Node(50);    (root.child).add(new Node(2));    (root.child).add(new Node(30));    (root.child).add(new Node(14));    (root.child).add(new Node(60));    (root.child.get(0).child).add(new Node(15));    (root.child.get(0).child).add(new Node(25));    (root.child.get(0).child.get(1).child).add(new Node(70));    (root.child.get(0).child.get(1).child).add(new Node(100));    (root.child.get(1).child).add(new Node(6));    (root.child.get(1).child).add(new Node(1));    (root.child.get(2).child).add(new Node(7));    (root.child.get(2).child.get(0).child).add(new Node(17));    (root.child.get(2).child.get(0).child).add(new Node(99));    (root.child.get(2).child.get(0).child).add(new Node(27));    (root.child.get(3).child).add(new Node(16));     // Node whose number of    // siblings is to be calculated    int x = 100;     // Function calling    System.out.println( numberOfSiblings(root, x) );}} // This code is contributed by Arnab Kundu
# Python3 program to find number# of siblings of a given nodefrom queue import Queue # Represents a node of an n-ary treeclass newNode:    def __init__(self,data):        self.child = []        self.key = data # Function to calculate number# of siblings of a given nodedef numberOfSiblings(root, x):    if (root == None):        return 0     # Creating a queue and    # pushing the root    q = Queue()    q.put(root)     while (not q.empty()):                 # Dequeue an item from queue and        # check if it is equal to x If YES,        # then return number of children        p = q.queue[0]        q.get()         # Enqueue all children of        # the dequeued item        for i in range(len(p.child)):                         # If the value of children            # is equal to x, then return            # the number of siblings            if (p.child[i].key == x):                return len(p.child) - 1            q.put(p.child[i]) # Driver Codeif __name__ == '__main__':     # Creating a generic tree as    # shown in above figure    root = newNode(50)    (root.child).append(newNode(2))    (root.child).append(newNode(30))    (root.child).append(newNode(14))    (root.child).append(newNode(60))    (root.child[0].child).append(newNode(15))    (root.child[0].child).append(newNode(25))    (root.child[0].child[1].child).append(newNode(70))    (root.child[0].child[1].child).append(newNode(100))    (root.child[1].child).append(newNode(6))    (root.child[1].child).append(newNode(1))    (root.child[2].child).append(newNode(7))    (root.child[2].child[0].child).append(newNode(17))    (root.child[2].child[0].child).append(newNode(99))    (root.child[2].child[0].child).append(newNode(27))    (root.child[3].child).append(newNode(16))     # Node whose number of    # siblings is to be calculated    x = 100     # Function calling    print(numberOfSiblings(root, x)) # This code is contributed by PranchalK
// C# program to find number// of siblings of a 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;     public Node(int data)    {        key = data;        child = new List<Node>();    }}; // Function to calculate number// of siblings of a given nodestatic int numberOfSiblings(Node root, int x){    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)    {        // 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();         // Enqueue all children of        // the dequeued item        for (int i = 0; i < p.child.Count; i++)        {            // If the value of children            // is equal to x, then return            // the number of siblings            if (p.child[i].key == x)                return p.child.Count - 1;            q.Enqueue(p.child[i]);        }    }    return -1;} // Driver codepublic static void Main(String []args){    // Creating a generic tree    // as shown in above figure    Node root = new Node(50);    (root.child).Add(new Node(2));    (root.child).Add(new Node(30));    (root.child).Add(new Node(14));    (root.child).Add(new Node(60));    (root.child[0].child).Add(new Node(15));    (root.child[0].child).Add(new Node(25));    (root.child[0].child[1].child).Add(new Node(70));    (root.child[0].child[1].child).Add(new Node(100));    (root.child[1].child).Add(new Node(6));    (root.child[1].child).Add(new Node(1));    (root.child[2].child).Add(new Node(7));    (root.child[2].child[0].child).Add(new Node(17));    (root.child[2].child[0].child).Add(new Node(99));    (root.child[2].child[0].child).Add(new Node(27));    (root.child[3].child).Add(new Node(16));     // Node whose number of    // siblings is to be calculated    int x = 100;     // Function calling    Console.WriteLine( numberOfSiblings(root, x));}} // This code is contributed by PrinciRaj1992
<script> // JavaScript program to find number// of siblings of a given node // Represents a node of an n-ary treeclass Node{  constructor(data)  {    this.key = data;    this.child = [];  }}; // Function to calculate number// of siblings of a given nodefunction numberOfSiblings(root, x){    if (root == null)        return 0;     // Creating a queue and    // pushing the root    var q = [];    q.push(root);     while (q.length > 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();         // push all children of        // the dequeued item        for (var i = 0; i < p.child.length; i++)        {            // If the value of children            // is equal to x, then return            // the number of siblings            if (p.child[i].key == x)                return p.child.length - 1;            q.push(p.child[i]);        }    }    return -1;} // Driver code// Creating a generic tree// as shown in above figurevar root = new Node(50);(root.child).push(new Node(2));(root.child).push(new Node(30));(root.child).push(new Node(14));(root.child).push(new Node(60));(root.child[0].child).push(new Node(15));(root.child[0].child).push(new Node(25));(root.child[0].child[1].child).push(new Node(70));(root.child[0].child[1].child).push(new Node(100));(root.child[1].child).push(new Node(6));(root.child[1].child).push(new Node(1));(root.child[2].child).push(new Node(7));(root.child[2].child[0].child).push(new Node(17));(root.child[2].child[0].child).push(new Node(99));(root.child[2].child[0].child).push(new Node(27));(root.child[3].child).push(new Node(16));// Node whose number of// siblings is to be calculatedvar x = 100;// Function callingdocument.write( numberOfSiblings(root, x));  </script>
1
 
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.  
YouTubeGeeksforGeeks507K subscribersNumber of siblings of a 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:02•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Zm8SMMtJkF8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
sahilkhoslaa
PranchalKatiyar
andrew1234
princiraj1992
razor7386
rrrtnx
cpp-queue
Queue
Tree
Queue
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Construct Complete Binary Tree from its Linked List Representation
Iterative Letter Combinations of a Phone Number
FIFO (First-In-First-Out) approach in Programming
Applications of Priority Queue
Reversing a Queue
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion