Find the Level of a Binary Tree with Width K | Structure of binary tree node ; Function to create new node ; Function returns required level of width k , if found else - 1 ; To store the node and the label and perform traversal ; Taking the last label of each level of the tree ; Check width of current level ; If the width is equal to k then return that level ; Taking the first label of each level of the tree ; If any level does not has width equal to k , return - 1 ; Driver code
class Node { constructor ( ) { this . data = 0 ; this . left = null ; this . right = null ; } } ; class pair { constructor ( first , second ) { this . first = first ; this . second = second ; } } function newNode ( data ) { var temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } function findLevel ( root , k , level ) { var qt = [ ] ; qt . push ( new pair ( root , 0 ) ) ; var count = 1 , b = 0 , a = 0 ; while ( qt . length != 0 ) { var temp = qt . shift ( ) ; if ( count == 1 ) { b = temp . second ; } if ( temp . first . left != null ) { qt . push ( new pair ( temp . first . left , 2 * temp . second ) ) ; } if ( temp . first . right != null ) { qt . push ( new pair ( temp . first . right , 2 * temp . second + 1 ) ) ; } count -- ; if ( count == 0 ) { if ( ( b - a + 1 ) == k ) return level ; var secondLabel = qt [ 0 ] ; a = secondLabel . second ; level += 1 ; count = qt . length ; } } return - 1 ; } var root = newNode ( 5 ) ; root . left = newNode ( 6 ) ; root . right = newNode ( 2 ) ; root . right . right = newNode ( 8 ) ; root . left . left = newNode ( 7 ) ; root . left . left . left = newNode ( 5 ) ; root . left . right = newNode ( 3 ) ; root . left . right . right = newNode ( 4 ) ; var k = 4 ; document . write ( findLevel ( root , k , 1 ) ) ;