Maximum width of a binary tree | Java program to calculate maximum width of a binary tree using queue ; A binary tree node has data , pointer to left child and a pointer to right child ; Function to find the maximum width of the tree using level order traversal ; Base case ; Initialize result ; Do Level order traversal keeping track of number of nodes at every level ; Get the size of queue when the level order traversal for one level finishes ; Update the maximum node count value ; Iterate for all the nodes in the queue currently ; Dequeue an node from queue ; Enqueue left and right children of dequeued node ; Driver code ; Function call
import java . util . LinkedList ; import java . util . Queue ; public class maxwidthusingqueue { static class node { int data ; node left , right ; public node ( int data ) { this . data = data ; } } static int maxwidth ( node root ) { if ( root == null ) return 0 ; int maxwidth = 0 ; Queue < node > q = new LinkedList < > ( ) ; q . add ( root ) ; while ( ! q . isEmpty ( ) ) { int count = q . size ( ) ; maxwidth = Math . max ( maxwidth , count ) ; while ( count -- > 0 ) { node temp = q . remove ( ) ; if ( temp . left != null ) { q . add ( temp . left ) ; } if ( temp . right != null ) { q . add ( temp . right ) ; } } } return maxwidth ; } public static void main ( String [ ] args ) { node root = new node ( 1 ) ; root . left = new node ( 2 ) ; root . right = new node ( 3 ) ; root . left . left = new node ( 4 ) ; root . left . right = new node ( 5 ) ; root . right . right = new node ( 8 ) ; root . right . right . left = new node ( 6 ) ; root . right . right . right = new node ( 7 ) ; System . out . println ( " Maximum ▁ width ▁ = ▁ " + maxwidth ( root ) ) ; } }