Level with maximum number of nodes | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } int maxNodeLevel ( Node * root ) { if ( root == NULL ) return -1 ; queue < Node * > q ; q . push ( root ) ; int level = 0 ; int max = INT_MIN ; int level_no = 0 ; while ( 1 ) { int NodeCount = q . size ( ) ; if ( NodeCount == 0 ) break ; if ( NodeCount > max ) { max = NodeCount ; level_no = level ; } while ( NodeCount > 0 ) { Node * Node = q . front ( ) ; q . pop ( ) ; if ( Node -> left != NULL ) q . push ( Node -> left ) ; if ( Node -> right != NULL ) q . push ( Node -> right ) ; NodeCount -- ; } level ++ ; } return level_no ; } int main ( ) { struct 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 ) ; printf ( " Level ▁ having ▁ maximum ▁ number ▁ of ▁ Nodes ▁ : ▁ % d " , maxNodeLevel ( root ) ) ; return 0 ; }