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 program ; Creating a generic tree as shown in above figure ; Node whose number of siblings is to be calculated ; Function calling
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int key ; vector < Node * > child ; Node ( int data ) { key = data ; } } ; int numberOfSiblings ( Node * root , int x ) { if ( root == NULL ) return 0 ; queue < Node * > q ; q . push ( root ) ; while ( ! q . empty ( ) ) { Node * p = q . front ( ) ; q . pop ( ) ; for ( int i = 0 ; i < p -> child . size ( ) ; i ++ ) { if ( p -> child [ i ] -> key == x ) return p -> child . size ( ) - 1 ; q . push ( p -> child [ i ] ) ; } } } int main ( ) { 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 ) ) ; int x = 100 ; cout << numberOfSiblings ( root , x ) << endl ; return 0 ; }