Number of siblings of a given Node in n | Python3 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
from queue import Queue NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . child = [ ] NEW_LINE self . key = data NEW_LINE DEDENT DEDENT def numberOfSiblings ( root , x ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT q = Queue ( ) NEW_LINE q . put ( root ) NEW_LINE while ( not q . empty ( ) ) : NEW_LINE INDENT p = q . queue [ 0 ] NEW_LINE q . get ( ) NEW_LINE for i in range ( len ( p . child ) ) : NEW_LINE INDENT if ( p . child [ i ] . key == x ) : NEW_LINE INDENT return len ( p . child ) - 1 NEW_LINE DEDENT q . put ( p . child [ i ] ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 50 ) NEW_LINE ( root . child ) . append ( newNode ( 2 ) ) NEW_LINE ( root . child ) . append ( newNode ( 30 ) ) NEW_LINE ( root . child ) . append ( newNode ( 14 ) ) NEW_LINE ( root . child ) . append ( newNode ( 60 ) ) NEW_LINE ( root . child [ 0 ] . child ) . append ( newNode ( 15 ) ) NEW_LINE ( root . child [ 0 ] . child ) . append ( newNode ( 25 ) ) NEW_LINE ( root . child [ 0 ] . child [ 1 ] . child ) . append ( newNode ( 70 ) ) NEW_LINE ( root . child [ 0 ] . child [ 1 ] . child ) . append ( newNode ( 100 ) ) NEW_LINE ( root . child [ 1 ] . child ) . append ( newNode ( 6 ) ) NEW_LINE ( root . child [ 1 ] . child ) . append ( newNode ( 1 ) ) NEW_LINE ( root . child [ 2 ] . child ) . append ( newNode ( 7 ) ) NEW_LINE ( root . child [ 2 ] . child [ 0 ] . child ) . append ( newNode ( 17 ) ) NEW_LINE ( root . child [ 2 ] . child [ 0 ] . child ) . append ( newNode ( 99 ) ) NEW_LINE ( root . child [ 2 ] . child [ 0 ] . child ) . append ( newNode ( 27 ) ) NEW_LINE ( root . child [ 3 ] . child ) . append ( newNode ( 16 ) ) NEW_LINE x = 100 NEW_LINE print ( numberOfSiblings ( root , x ) ) NEW_LINE DEDENT