Print siblings of a given Node in N | Java 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
import java . util . * ; class GFG { static class Node { int key ; Vector < Node > child = new Vector < > ( ) ; } ; static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . key = key ; return temp ; } static void Siblings ( Node root , int value ) { int flag = 0 ; if ( root == null ) return ; Queue < Node > q = new LinkedList < > ( ) ; q . add ( root ) ; while ( ! q . isEmpty ( ) ) { Node temp = q . peek ( ) ; q . remove ( ) ; for ( int i = 0 ; i < temp . child . size ( ) ; i ++ ) { if ( temp . child . get ( i ) . key == value ) { flag = 1 ; for ( int j = 0 ; j < temp . child . size ( ) ; j ++ ) { if ( value != temp . child . get ( j ) . key ) System . out . print ( temp . child . get ( j ) . key + " ▁ " ) ; } break ; } q . add ( temp . child . get ( i ) ) ; } } if ( flag == 0 ) System . out . print ( " No ▁ siblings ! ! " ) ; } static Node constructTree ( ) { Node root = newNode ( 10 ) ; ( root . child ) . add ( newNode ( 20 ) ) ; ( root . child ) . add ( newNode ( 30 ) ) ; ( root . child ) . add ( newNode ( 40 ) ) ; ( root . child . get ( 0 ) . child ) . add ( newNode ( 50 ) ) ; ( root . child . get ( 0 ) . child ) . add ( newNode ( 60 ) ) ; ( root . child . get ( 1 ) . child ) . add ( newNode ( 70 ) ) ; ( root . child . get ( 1 ) . child ) . add ( newNode ( 80 ) ) ; ( root . child . get ( 2 ) . child ) . add ( newNode ( 90 ) ) ; ( root . child . get ( 2 ) . child ) . add ( newNode ( 100 ) ) ; ( root . child . get ( 2 ) . child ) . add ( newNode ( 110 ) ) ; return root ; } public static void main ( String [ ] args ) { Node root = constructTree ( ) ; int X = 30 ; Siblings ( root , X ) ; } }