Given a Binary Tree and an integer K, the task is to find the level of the Binary Tree with width K. If multiple levels exists with width K, print the lowest level. If no such level exists, print -1.

The width of a level of a Binary tree is defined as the number of nodes between leftmost and the rightmost node at that level, including the NULL nodes in between them as well.

Examples:

Input:_ K = 4_

          5  --------- 1st level width = 1 => (5)
        /   \
       6     2 -------- 2nd level width = 2 => (6, 2)
      / \     \  
     7   3     8 -------3rd level width = 4 => (7, 3, NULL, 8)
    /     \
   5       4  -----------4th level width = 4 => (5, NULL, NULL, 4)

Output:_ 3_

Explanation:

For the given tree, the levels having width K( = 4) are 3 and 4.

Since 3 is the minimum of the two, print the minimum.

Input:_ K = 7_

           1  --------- 1st level width = 1 => (1)
         /   \
        2     9 -------- 2nd level width = 2 => (2, 9)
       /       \  
      7         8 ---------3rd level width = 4 => (7, NULL, NULL, 8)
     /         /
    5         9 -----------4th level width = 7 => (5, NULL, NULL, 
             /                                NULL, NULL, NULL, 9)
            2  -----------5th level width = 1 => (2)
           /
          1  -----------6th level width = 1 => (1)

Output:_ 4_

Explanation:

For the given tree, the level having width K( = 7) is 4.

#data structures #searching #tree #cpp-queue #tree traversals #data analysis

Find the Level of a Binary Tree with Width K
1.50 GEEK