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

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++

 // C++ program to find number// of siblings of a given node#include using namespace std; // Represents a node of an n-ary treeclass Node {public:    int key;    vector 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 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

## Python3

 # Python3 program to find number # of siblings of a given node from queue import Queue  # Represents a node of an n-ary tree class newNode:     def __init__(self,data):        self.child = []        self.key = data # Function to calculate number # of siblings of a given node def 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#

## Javascript



Output
1

Complexity Analysis:

• 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.

### Example no 2:

#### Algorithmic steps for implementing the given concept:

Create a hash map to store the parent of each node.
For each node in the tree, map it to its parent in the hash map.
Given the node for which you want to find the number of siblings, look up its parent in the hash map.
If the parent is not found, return 0 as the node has no siblings.
If the parent is found, count the number of children the parent has.
Return the count minus 1 as the given node is included in the count.

Note: This algorithm assumes that the parent array is complete and accurately represents the n-ary tree.

## C++

 #include #include #include  using namespace std; int findSiblingCount(int node, unordered_map> &treeMap) {    int parent = treeMap.count(node) ? treeMap[node][0] : -1;    if (parent == -1) {        return 0;    }     int siblingCount = treeMap[parent].size() - 1;    return siblingCount;} int main() {    unordered_map> treeMap;    treeMap[0] = {-1, 1, 2, 3};    treeMap[1] = {0, 4, 5};    treeMap[2] = {0, 6};    treeMap[3] = {0};    treeMap[4] = {1};    treeMap[5] = {1};    treeMap[6] = {2};     int node = 4;    cout << "The number of siblings for node " << node << " is: " << findSiblingCount(node, treeMap) << endl;    return 0;}

## Java

## Python3

 def findSiblingCount(node, treeMap):    parent = treeMap[node][0] if node in treeMap else -1    if parent == -1:        return 0         siblingCount = len(treeMap[parent]) - 1    return siblingCount treeMap = {    0: [-1, 1, 2, 3],    1: [0, 4, 5],    2: [0, 6],    3: [0],    4: [1],    5: [1],    6: [2]} node = 4print(f"The number of siblings for node {node} is: {findSiblingCount(node, treeMap)}")

## Javascript

 // Creating a new Map to represent the tree structurelet treeMap = new Map(); // Adding nodes and their children to the treeMaptreeMap.set(0, [-1, 1, 2, 3]);treeMap.set(1, [0, 4, 5]);treeMap.set(2, [0, 6]);treeMap.set(3, [0]);treeMap.set(4, [1]);treeMap.set(5, [1]);treeMap.set(6, [2]); // Function to find the number of siblings for a given node in the treeMapfunction findSiblingCount(node, treeMap) {   // Finding the parent node of the given node  let parent = treeMap.has(node) ? treeMap.get(node)[0] : -1;   // If the given node does not have a parent, it has no siblings  if (parent === -1) {      return 0;  }   // Finding the number of siblings for the given node   // by subtracting 1 from the length of the parent node's children array  let siblingCount = treeMap.get(parent).length - 1;  return siblingCount;} // Example usage of the function to find the number of siblings for a given nodelet node = 4; console.log(`The number of siblings for node \${node} is: \${findSiblingCount(node, treeMap)}`); // This code is contributed by Amit Mangal.

## C#

 // Import required namespacesusing System;using System.Collections.Generic; class Program{  // Function to find the number of siblings of a given node in a tree  static int FindSiblingCount(int node, Dictionary> treeMap)  {  // Find the parent of the given node  int parent = treeMap.ContainsKey(node) ? treeMap[node][0] : -1;         // If the node does not have a parent, return 0      if (parent == -1)      {          return 0;      }       // Find the number of siblings of the node      int siblingCount = treeMap[parent].Count - 1;      return siblingCount;  }   static void Main(string[] args)  {      // Create the tree as a dictionary      Dictionary> treeMap = new Dictionary>();      treeMap[0] = new List { -1, 1, 2, 3 };      treeMap[1] = new List { 0, 4, 5 };      treeMap[2] = new List { 0, 6 };      treeMap[3] = new List { 0 };      treeMap[4] = new List { 1 };      treeMap[5] = new List { 1 };      treeMap[6] = new List { 2 };       // Define the node to find the number of siblings for      int node = 4;       // Print the result      Console.WriteLine("The number of siblings for node " + node + " is: " + FindSiblingCount(node, treeMap));  }} // This code is contributed by Amit Mangal

Output
The number of siblings for node 4 is: 2

#### Explanation:

In this implementation, the findSiblingCount function takes a node and the tree represented as a hash map as inputs and returns the number of siblings the node has. If the node is not found in the tree map, it returns 0 as the node has no siblings. If the node is found, the function looks up the parent of the node in the tree map and returns the number of children the parent has minus 1, which represents the number of siblings the node has.

#### Time and Space complexities for above program:

The time complexity of the above code is O(1) because the findSiblingCount function takes constant time to find the number of siblings of a given node. This is because the hash map is used to store the parent of each node, so looking up the parent of a given node takes constant time. The same holds true for counting the number of children the parent has.

The space complexity of the above code is O(n), where n is the number of nodes in the n-ary tree. This is because the hash map is used to store the parent of each node and the children of each parent, so the space required is proportional to the number of nodes in the tree.

Note: The space complexity assumes that the hash map is used to represent the tree and the number of children each node has is constant, so the space used is linear in the number of nodes. If the number of children each node has is not constant, the space complexity would be higher.

Previous
Next