Print the middle nodes of each level of a Binary Tree | C # 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
using System ; using System . Collections ; using System . Collections . Generic ; class GFG { static Dictionary < int , ArrayList > M ; class node { public int data ; public node left ; public node right ; public node ( int data , node left , node right ) { this . data = data ; this . left = left ; this . right = right ; } } ; static node newnode ( int d ) { node temp = new node ( d , null , null ) ; return temp ; } static void dfs ( node root , int l ) { if ( root == null ) return ; if ( ! M . ContainsKey ( l ) ) { ArrayList temp = new ArrayList ( ) ; temp . Add ( root . data ) ; M [ l ] = temp ; } else M [ l ] . Add ( root . data ) ; dfs ( root . left , l + 1 ) ; dfs ( root . right , l + 1 ) ; } static void printMidNodes ( node root ) { M = new Dictionary < int , ArrayList > ( ) ; dfs ( root , 0 ) ; foreach ( KeyValuePair < int , ArrayList > it in M ) { int size = it . Value . Count ; if ( size % 2 == 1 ) { Console . Write ( it . Value [ ( size - 1 ) / 2 ] + " STRNEWLINE " ) ; } else { Console . Write ( it . Value [ ( size - 1 ) / 2 ] + " ▁ " + it . Value [ ( ( size - 1 ) / 2 ) + 1 ] + " STRNEWLINE " ) ; } } } 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 ) ; } }