Number of siblings of a given Node in n | C # program to find number of siblings of a given node ; Represents a node of an n - ary tree ; Function to calculate number of siblings of a given node ; Creating a queue and pushing the root ; Dequeue an item from queue and check if it is equal to x If YES , then return number of children ; Enqueue all children of the dequeued item ; If the value of children is equal to x , then return the number of siblings ; Driver code ; Creating a generic tree as shown in above figure ; Node whose number of siblings is to be calculated ; Function calling
using System ; using System . Collections . Generic ; class GFG { public class Node { public int key ; public List < Node > child ; public Node ( int data ) { key = data ; child = new List < Node > ( ) ; } } ; static int numberOfSiblings ( Node root , int x ) { if ( root == null ) return 0 ; Queue < Node > q = new Queue < Node > ( ) ; q . Enqueue ( root ) ; while ( q . Count > 0 ) { Node p = q . Peek ( ) ; q . Dequeue ( ) ; for ( int i = 0 ; i < p . child . Count ; i ++ ) { if ( p . child [ i ] . key == x ) return p . child . Count - 1 ; q . Enqueue ( p . child [ i ] ) ; } } return - 1 ; } public static void Main ( String [ ] args ) { 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 ) ) ; int x = 100 ; Console . WriteLine ( numberOfSiblings ( root , x ) ) ; } }