Print the middle nodes of each level of a Binary Tree | Javascript program for the above approach ; Structure Node of Binary Tree ; Function to create a new node ; Return the created node ; Function that performs the DFS traversal on Tree to store all the nodes at each level in map M ; Base Case ; Push the current level node ; Left Recursion ; Right Recursion ; Function that print all the middle nodes for each level in Binary Tree ; Stores all node in each level ; Perform DFS traversal ; Traverse the map M ; Get the size of vector ; For odd number of elements ; Print ( M / 2 ) th Element ; Otherwise ; Print ( M / 2 ) th and ( M / 2 + 1 ) th Element ; Given Tree ; Function Call
var M = new Map ( ) ; class node { constructor ( data , left , right ) { this . data = data ; this . left = left ; this . right = right ; } } ; function newnode ( d ) { var temp = new node ( d , null , null ) ; return temp ; } function dfs ( root , l ) { if ( root == null ) return ; if ( ! M . has ( l ) ) { var temp = [ ] ; temp . push ( root . data ) ; M . set ( l , temp ) ; } else { var temp = M . get ( l ) ; temp . push ( root . data ) ; M . set ( l , temp ) ; } dfs ( root . left , l + 1 ) ; dfs ( root . right , l + 1 ) ; } function printMidNodes ( root ) { M = new Map ( ) ; dfs ( root , 0 ) ; M . forEach ( ( value , key ) => { var size = value . length ; if ( size % 2 == 1 ) { document . write ( value [ parseInt ( ( size - 1 ) / 2 ) ] + " " ) ; } else { document . write ( value [ parseInt ( ( size - 1 ) / 2 ) ] + " " + value [ parseInt ( ( ( size - 1 ) / 2 ) + 1 ) ] + " " ) ; } } ) ; } var root = newnode ( 1 ) ; root . left = newnode ( 2 ) ; root . right = newnode ( 3 ) ; root . left . left = newnode ( 4 ) ; root . left . right = newnode ( 5 ) ; root . left . right . left = newnode ( 11 ) ; root . left . right . right = newnode ( 6 ) ; root . left . right . right . left = newnode ( 7 ) ; root . left . right . right . right = newnode ( 9 ) ; root . right . left = newnode ( 10 ) ; root . right . right = newnode ( 8 ) ; printMidNodes ( root ) ;