Open In App

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

Last Updated : 14 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
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.



Similar Reads

Print siblings of a given Node in N-ary Tree
Given an N-ary tree and an element X, the task is to print the siblings of the node with value X. Two nodes are considered to be siblings if they are present at the same level and have the same parent. Examples: Input: X = 100 Output: 90 110Explanation: Nodes valued 90, 100 and 110 have the same parent, i.e. the node valued 40. Therefore, nodes 90
8 min read
Find the parent node of maximum product Siblings in given Binary Tree
Given a binary tree, the task is to find the node whose children have maximum Sibling product in the given Binary Tree. If there are multiple such nodes, return the node which has the maximum value. Examples: Input: Tree: 4 / \ 5 2 / \ 3 1 / \6 12Output: 3Explanation: For the above tree, the maximum product for the siblings is formed for nodes 6 an
15+ min read
Path from the root node to a given node in an N-ary Tree
Given an integer N and an N-ary Tree of the following form: Every node is numbered sequentially, starting from 1, till the last level, which contains the node N.The nodes at every odd level contains 2 children and nodes at every even level contains 4 children. The task is to print the path from the root node to the node N. Examples: Input: N = 14 O
10 min read
Check if two nodes in a Binary Tree are siblings
Given a binary tree and two nodes, the task is to check if the nodes are siblings of each other or not. Two nodes are said to be siblings if they are present at the same level, and their parents are the same. Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7First node is 4 and Second node is 6.Output : No, they are not siblings.Input : 1 / \ 5 6 / / \ 7
7 min read
Find the maximum GCD of the siblings of a Binary Tree
Given a 2d-array arr[][] which represents the nodes of a Binary tree, the task is to find the maximum GCD of the siblings of this tree without actually constructing it. Example:   Input: arr[][] = {{4, 5}, {4, 2}, {2, 3}, {2, 1}, {3, 6}, {3, 12}} Output: 6 Explanation:   For the above tree, the maximum GCD for the siblings is formed for the nodes 6
11 min read
Number of children of given node in n-ary Tree
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 : 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 child
7 min read
Minimize operations to convert each node of N-ary Tree from initial[i] to final[i] by flipping current node subtree in alternate fashion
Given an N-ary Tree consisting of N nodes valued from [0, N - 1] and two binary arrays initial[] and final[] of size N such that initial[i] represents the value assigned to the node i, the task is to find the minimum number of operations required to convert each value of nodes initial[i] to final[i] by flipping the value of the node, its grandchild
11 min read
Find GCD of each subtree of a given node in an N-ary Tree for Q queries
Given an N-ary Tree containing N nodes, values associated with each node and Q queries, where each query contains a single node. The task is to find the GCD of values of all the nodes present in the subtree (including itself). Example: Tree: 1(2) / \ / \ 2(3) 3(4) / \ / \ 4(8) 5(16) query[]: {2, 3, 1} Output: {3, 4, 1} Explanation: For query 1: GCD
10 min read
Queries to calculate Bitwise OR of each subtree of a given node in an N-ary Tree
Given an N-ary Tree consisting of N nodes valued from 1 to N, an array arr[] consisting of N positive integers, where arr[i] is the value associated with the ith node, and Q queries, each consisting of a node. The task for each query is to find the Bitwise OR of node values present in the subtree of the given node. Examples: Input: arr[] = {2, 3, 4
11 min read
Replace each node in given N-ary Tree with sum of all its subtrees
Given an N-ary tree. The task is to replace the values of each node with the sum of all its subtrees and the node itself. Examples Input: 1 / | \ 2 3 4 / \ \ 5 6 7Output: Initial Pre-order Traversal: 1 2 5 6 7 3 4 Final Pre-order Traversal: 28 20 5 6 7 3 4 Explanation: Value of each node is replaced by the sum of all its subtrees and the node itsel
8 min read
Article Tags :
Practice Tags :