Print the nodes of the Binary Tree whose height is a Prime number | Javascript implementation of nodes at prime height in the given tree ; To store Prime Numbers ; To store height of each node ; Function to find the prime numbers till 10 ^ 5 ; Traverse all multiple of i and make it false ; Function to perform dfs ; Store the height of node ; Function to find the nodes at prime height ; To precompute prime number till 10 ^ 5 ; Check if height [ node ] is prime ; Number of nodes ; Edges of the tree
let MAX = 100000 ; let graph = [ ] for ( let i = 0 ; i < MAX + 1 ; i ++ ) { graph . push ( [ ] ) } let Prime = new Array ( MAX + 1 ) . fill ( true ) ; let height = new Array ( MAX + 1 ) ; function SieveOfEratosthenes ( ) { let i , j ; Prime [ 0 ] = Prime [ 1 ] = false ; for ( i = 2 ; i * i <= MAX ; i ++ ) { if ( Prime [ i ] ) { for ( j = 2 * i ; j < MAX ; j += i ) { Prime [ j ] = false ; } } } } function dfs ( node , parent , h ) { height [ node ] = h ; for ( let to of graph [ node ] ) { if ( to == parent ) continue ; dfs ( to , node , h + 1 ) ; } } function primeHeightNode ( N ) { SieveOfEratosthenes ( ) ; for ( let i = 1 ; i <= N ; i ++ ) { if ( Prime [ height [ i ] ] ) { document . write ( i + " " ) ; } } } let N = 5 ; graph [ 1 ] . push ( 2 ) ; graph [ 1 ] . push ( 3 ) ; graph [ 2 ] . push ( 4 ) ; graph [ 2 ] . push ( 5 ) ; dfs ( 1 , 1 , 0 ) ; primeHeightNode ( N ) ;