Print the middle nodes of each level of a Binary Tree | 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
class node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newnode ( d ) : NEW_LINE INDENT temp = node ( d ) NEW_LINE return temp NEW_LINE DEDENT def dfs ( root , l , M ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if l not in M : NEW_LINE INDENT M [ l ] = [ ] NEW_LINE DEDENT M [ l ] . append ( root . data ) NEW_LINE dfs ( root . left , l + 1 , M ) NEW_LINE dfs ( root . right , l + 1 , M ) NEW_LINE DEDENT def printMidNodes ( root ) : NEW_LINE INDENT M = dict ( ) NEW_LINE dfs ( root , 0 , M ) NEW_LINE for it in M . values ( ) : NEW_LINE INDENT size = len ( it ) NEW_LINE if ( size & 1 ) : NEW_LINE INDENT print ( it [ ( size - 1 ) // 2 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( str ( it [ ( size - 1 ) // 2 ] ) + ' ▁ ' + str ( it [ ( size - 1 ) // 2 + 1 ] ) ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = newnode ( 1 ) NEW_LINE root . left = newnode ( 2 ) NEW_LINE root . right = newnode ( 3 ) NEW_LINE root . left . left = newnode ( 4 ) NEW_LINE root . left . right = newnode ( 5 ) NEW_LINE root . left . right . left = newnode ( 11 ) NEW_LINE root . left . right . right = newnode ( 6 ) NEW_LINE root . left . right . right . left = newnode ( 7 ) NEW_LINE root . left . right . right . right = newnode ( 9 ) NEW_LINE root . right . left = newnode ( 10 ) NEW_LINE root . right . right = newnode ( 8 ) NEW_LINE printMidNodes ( root ) NEW_LINE DEDENT