Open In App

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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 <bits/stdc++.h>
using namespace std;
 
// Represents a node of an n-ary tree
class Node {
public:
    int key;
    vector<Node*> child;
 
    Node(int data)
    {
        key = data;
    }
};
 
// Function to calculate number
// of siblings of a given node
int 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 program
int 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




// Java program to find number
// of siblings of a given node
import java.util.*;
 
public class GFG
{
     
// Represents a node of an n-ary tree
static 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 node
static 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 code
public 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




# 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 Code
if __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#




// C# program to find number
// of siblings of a given node
using System;
using System.Collections.Generic;
     
class GFG
{
     
// Represents a node of an n-ary tree
public 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 node
static 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 code
public 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


Javascript




<script>
 
// JavaScript program to find number
// of siblings of a given node
 
// Represents a node of an n-ary tree
class Node
{
  constructor(data)
  {
    this.key = data;
    this.child = [];
  }
};
 
// Function to calculate number
// of siblings of a given node
function 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 figure
var 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 calculated
var x = 100;
// Function calling
document.write( numberOfSiblings(root, x));
 
 
</script>


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.

Program: Implementing the given concept by using hash map:

C++




#include <iostream>
#include <vector>
#include <unordered_map>
 
using namespace std;
 
int findSiblingCount(int node, unordered_map<int, vector<int>> &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<int, vector<int>> 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




import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class SiblingCounter {
 
    // Define method to count the number of siblings for a
    // given node in a tree
    public static int findSiblingCount(int node,Map<Integer, List<Integer> > treeMap)
    {
        int parent = treeMap.containsKey(node)
                         ? treeMap.get(node).get(0)
                         : -1;
        if (parent == -1) {
            return 0;
        }
        int siblingCount = treeMap.get(parent).size() - 1;
        return siblingCount;
    }
 
    public static void main(String[] args)
    {
        // Define the tree using an unordered map of integer
        // keys and vector values
        Map<Integer, List<Integer> > treeMap = new HashMap<>();
        treeMap.put(0, new ArrayList<Integer>() {{add(-1);
                add(1);
                add(2);
                add(3);
            }
        });
        treeMap.put(1, new ArrayList<Integer>() {
            {
                add(0);
                add(4);
                add(5);
            }
        });
        treeMap.put(2, new ArrayList<Integer>() {
            {
                add(0);
                add(6);
            }
        });
        treeMap.put(3, new ArrayList<Integer>() {
            {
                add(0);
            }
        });
        treeMap.put(4, new ArrayList<Integer>() {
            {
                add(1);
            }
        });
        treeMap.put(5, new ArrayList<Integer>() {
            {
                add(1);
            }
        });
        treeMap.put(6, new ArrayList<Integer>() {
            {
                add(2);
            }
        });
 
        int node = 4;
        // Call the findSiblingCount method and print the
        // result
        System.out.println(
            "The number of siblings for node " + node
            + " is: " + findSiblingCount(node, treeMap));
    }
}


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 = 4
print(f"The number of siblings for node {node} is: {findSiblingCount(node, treeMap)}")


Javascript




// Creating a new Map to represent the tree structure
let treeMap = new Map();
 
// Adding nodes and their children to the treeMap
treeMap.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 treeMap
function 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 node
let 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 namespaces
using 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<int, List<int>> 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<int, List<int>> treeMap = new Dictionary<int, List<int>>();
      treeMap[0] = new List<int> { -1, 1, 2, 3 };
      treeMap[1] = new List<int> { 0, 4, 5 };
      treeMap[2] = new List<int> { 0, 6 };
      treeMap[3] = new List<int> { 0 };
      treeMap[4] = new List<int> { 1 };
      treeMap[5] = new List<int> { 1 };
      treeMap[6] = new List<int> { 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.



Last Updated : 14 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads