Level with maximum number of nodes | Python3 implementation to find the level having Maximum number of Nodes Importing Queue ; Helper class that allocates a new node with the given data and None left and right pointers . ; function to find the level having Maximum number of Nodes ; Current level ; Maximum Nodes at same level ; Level having Maximum Nodes ; Count Nodes in a level ; If it is Maximum till now Update level_no to current level ; Pop complete current level ; Increment for next level ; Driver Code ; binary tree formation 2 ; / \ ; 1 3 ; / \ \ ; 4 6 8 ; / ; 5 ;
from queue import Queue 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 maxNodeLevel ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT q = Queue ( ) NEW_LINE q . put ( root ) NEW_LINE level = 0 NEW_LINE Max = - 999999999999 NEW_LINE level_no = 0 NEW_LINE while ( 1 ) : NEW_LINE INDENT NodeCount = q . qsize ( ) NEW_LINE if ( NodeCount == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( NodeCount > Max ) : NEW_LINE INDENT Max = NodeCount NEW_LINE level_no = level NEW_LINE DEDENT while ( NodeCount > 0 ) : NEW_LINE INDENT Node = q . queue [ 0 ] NEW_LINE q . get ( ) NEW_LINE if ( Node . left != None ) : NEW_LINE INDENT q . put ( Node . left ) NEW_LINE DEDENT if ( Node . right != None ) : NEW_LINE INDENT q . put ( Node . right ) NEW_LINE DEDENT NodeCount -= 1 NEW_LINE DEDENT level += 1 NEW_LINE DEDENT return level_no NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 2 ) NEW_LINE root . left = newNode ( 1 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 8 ) NEW_LINE root . left . right . left = newNode ( 5 ) NEW_LINE print ( " Level ▁ having ▁ Maximum ▁ number ▁ of ▁ Nodes ▁ : ▁ " , maxNodeLevel ( root ) ) NEW_LINE DEDENT