Print siblings of a given Node in N | C ++ program for the above approach ; Structure of a node of N - ary tree ; Function to create a new node ; Function to find the siblings of the node value ; Stores nodes level wise ; Push the root ; Continue until all levels are traversed ; Stores current node ; Enqueue all children of the current node ; If node value is found ; Print all children of current node except value as the answer ; Push the child nodes of temp into the queue ; Driver Code ; Stores root of the constructed tree ; Print siblings of Node X
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; vector < Node * > child ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; return temp ; } void Siblings ( Node * root , int value ) { int flag = 0 ; if ( root == NULL ) return ; queue < Node * > q ; q . push ( root ) ; while ( ! q . empty ( ) ) { Node * temp = q . front ( ) ; q . pop ( ) ; for ( int i = 0 ; i < temp -> child . size ( ) ; i ++ ) { if ( temp -> child [ i ] -> key == value ) { flag = 1 ; for ( int j = 0 ; j < temp -> child . size ( ) ; j ++ ) { if ( value != temp -> child [ j ] -> key ) cout << temp -> child [ j ] -> key << " ▁ " ; } break ; } q . push ( temp -> child [ i ] ) ; } } if ( flag == 0 ) cout << " No ▁ siblings ! ! " ; } Node * constructTree ( ) { Node * root = newNode ( 10 ) ; ( root -> child ) . push_back ( newNode ( 20 ) ) ; ( root -> child ) . push_back ( newNode ( 30 ) ) ; ( root -> child ) . push_back ( newNode ( 40 ) ) ; ( root -> child [ 0 ] -> child ) . push_back ( newNode ( 50 ) ) ; ( root -> child [ 0 ] -> child ) . push_back ( newNode ( 60 ) ) ; ( root -> child [ 1 ] -> child ) . push_back ( newNode ( 70 ) ) ; ( root -> child [ 1 ] -> child ) . push_back ( newNode ( 80 ) ) ; ( root -> child [ 2 ] -> child ) . push_back ( newNode ( 90 ) ) ; ( root -> child [ 2 ] -> child ) . push_back ( newNode ( 100 ) ) ; ( root -> child [ 2 ] -> child ) . push_back ( newNode ( 110 ) ) ; return root ; } int main ( ) { Node * root = constructTree ( ) ; int X = 30 ; Siblings ( root , X ) ; return 0 ; }