Maximum width of an N | Function to find the maximum width of the tree using level order traversal ; Store the edges of the tree ; Stores maximum width of the tree ; Stores the nodes of each level ; Insert root node ; Perform level order traversal on the tree ; Stores the size of the queue ; Update maximum width ; Push the nodes of the next level and pop the elements of the current level ; Get element from the front the Queue ; Push all nodes of the next level . ; Return the result . ; Driver Code ; Constructed tree is : 1 / | \ 2 - 1 3 / \ \ 4 5 8 / / | \ 2 6 12 7
function maxWidth ( N , M , cost , s ) { let adj = [ ] ; for ( let i = 0 ; i < N ; i ++ ) { adj . push ( [ ] ) ; } for ( let i = 0 ; i < M ; i ++ ) { adj [ s [ i ] [ 0 ] ] . push ( s [ i ] [ 1 ] ) ; } let result = 0 ; let q = [ ] ; q . push ( 0 ) ; while ( q . length != 0 ) { let count = q . length ; result = Math . max ( count , result ) ; while ( count -- > 0 ) { let temp = q . shift ( ) ; for ( let i = 0 ; i < adj [ temp ] . length ; i ++ ) { q . push ( adj [ temp ] [ i ] ) ; } } } return result ; } let N = 11 , M = 10 ; let edges = [ ] ; edges . push ( [ 0 , 1 ] ) ; edges . push ( [ 0 , 2 ] ) ; edges . push ( [ 0 , 3 ] ) ; edges . push ( [ 1 , 4 ] ) ; edges . push ( [ 1 , 5 ] ) ; edges . push ( [ 3 , 6 ] ) ; edges . push ( [ 4 , 7 ] ) ; edges . push ( [ 6 , 10 ] ) ; edges . push ( [ 6 , 8 ] ) ; edges . push ( [ 6 , 9 ] ) ; let cost = [ 1 , 2 , - 1 , 3 , 4 , 5 , 8 , 2 , 6 , 12 , 7 ] ; document . write ( maxWidth ( N , M , cost , edges ) ) ;