Largest value in each level of Binary Tree | Set | Python program to print largest value on each level of binary tree ; Helper function that allocates a new node with the given data and None left and right pointers . ; put in the data ; function to find largest values ; if tree is empty ; push root to the queue ' q ' ; node count for the current level ; if true then all the nodes of the tree have been traversed ; maximum element for the current level ; get the front element from 'q   ; remove front element from 'q   ; if true , then update 'max   ; if left child exists ; if right child exists ; print maximum element of current level ; Driver Code ; Let us construct the following Tree 4 / \ 9 2 / \ \ 3 5 7 ; Function call
INT_MIN = - 2147483648 NEW_LINE class newNode : 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 largestValueInEachLevel ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT q = [ ] NEW_LINE nc = 10 NEW_LINE max = 0 NEW_LINE q . append ( root ) NEW_LINE while ( 1 ) : NEW_LINE INDENT nc = len ( q ) NEW_LINE if ( nc == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT max = INT_MIN NEW_LINE while ( nc ) : NEW_LINE INDENT front = q [ 0 ] NEW_LINE q = q [ 1 : ] NEW_LINE if ( max < front . data ) : NEW_LINE INDENT max = front . data NEW_LINE DEDENT if ( front . left ) : NEW_LINE INDENT q . append ( front . left ) NEW_LINE DEDENT if ( front . right != None ) : NEW_LINE INDENT q . append ( front . right ) NEW_LINE DEDENT nc -= 1 NEW_LINE DEDENT print ( max , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 4 ) NEW_LINE root . left = newNode ( 9 ) NEW_LINE root . right = newNode ( 2 ) NEW_LINE root . left . left = newNode ( 3 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE largestValueInEachLevel ( root ) NEW_LINE DEDENT