Level with maximum number of nodes | Java implementation to find the level having maximum number of Nodes ; A binary tree Node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL 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 program to test above ; binary tree formation ; 2 ; / \ ; 1 3 ; / \ \ ; 4 6 8 ; / ; 5
import java . util . * ; class GfG { static class Node { int data ; Node left ; Node right ; } static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = null ; node . right = null ; return ( node ) ; } static int maxNodeLevel ( Node root ) { if ( root == null ) return - 1 ; Queue < Node > q = new LinkedList < Node > ( ) ; q . add ( root ) ; int level = 0 ; int max = Integer . MIN_VALUE ; int level_no = 0 ; while ( true ) { int NodeCount = q . size ( ) ; if ( NodeCount == 0 ) break ; if ( NodeCount > max ) { max = NodeCount ; level_no = level ; } while ( NodeCount > 0 ) { Node Node = q . peek ( ) ; q . remove ( ) ; if ( Node . left != null ) q . add ( Node . left ) ; if ( Node . right != null ) q . add ( Node . right ) ; NodeCount -- ; } level ++ ; } return level_no ; } public static void main ( String [ ] args ) { Node root = newNode ( 2 ) ; root . left = newNode ( 1 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 6 ) ; root . right . right = newNode ( 8 ) ; root . left . right . left = newNode ( 5 ) ; System . out . println ( " Level ▁ having ▁ maximum ▁ number ▁ of ▁ Nodes ▁ : ▁ " + maxNodeLevel ( root ) ) ; } }