Print the middle nodes of each level of a Binary Tree | Java 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 ; Driver Code ; Given Tree ; Function Call
import java . util . * ; class GFG { static Map < Integer , Vector < Integer > > M ; static class node { int data ; node left ; node right ; public node ( ) { } public node ( int data , node left , node right ) { super ( ) ; this . data = data ; this . left = left ; this . right = right ; } } ; static node newnode ( int d ) { node temp = new node ( ) ; temp . data = d ; temp . left = null ; temp . right = null ; return temp ; } static void dfs ( node root , int l ) { if ( root == null ) return ; if ( ! M . containsKey ( l ) ) { Vector < Integer > temp = new Vector < Integer > ( ) ; temp . add ( root . data ) ; M . put ( l , temp ) ; } else M . get ( l ) . add ( root . data ) ; dfs ( root . left , l + 1 ) ; dfs ( root . right , l + 1 ) ; } static void printMidNodes ( node root ) { M = new HashMap < Integer , Vector < Integer > > ( ) ; dfs ( root , 0 ) ; for ( Map . Entry < Integer , Vector < Integer > > it : M . entrySet ( ) ) { int size = it . getValue ( ) . size ( ) ; if ( size % 2 == 1 ) { System . out . print ( it . getValue ( ) . get ( ( size - 1 ) / 2 ) + "NEW_LINE"); } else { System . out . print ( it . getValue ( ) . get ( ( size - 1 ) / 2 ) + " ▁ " + it . getValue ( ) . get ( ( ( size - 1 ) / 2 ) + 1 ) + "NEW_LINE"); } } } public static void main ( String [ ] args ) { node 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 ) ; } }