Find the Level of a Binary Tree with Width K
Last Updated :
22 Jun, 2021
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.
Approach:
The basic idea to solve the problem is to add a label to each node. If a parent has a label i, then assign a label 2*i to it’s left child and 2*i+1 to its right child. This will help in including the NULL nodes in the calculation.
Follow the steps below:
- Perform Level Order Traversal on the given tree using a Queue.
- Queue contains a pair of {Node, Label}. Initially insert {rootNode, 0} to queue.
- If parent has label i, then for a left child, insert {leftChild, 2*i} to queue and for right child, insert{rightChild, 2*i+1} into the queue.
- For each level assume a as label of leftmost node and b as label of rightmost node, then (b-a+1) gives the width of that level.
- Check whether the width is equal to K. If so, return level.
- If none of the levels have width K, then return -1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
struct Node *left, *right;
};
Node* newNode( int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
int findLevel(Node* root,
int k, int level)
{
queue<pair<Node*, int > > qt;
qt.push(make_pair(root, 0));
int count = 1, b, a = 0;
while (!qt.empty()) {
pair<Node*, int > temp = qt.front();
qt.pop();
if (count == 1) {
b = temp.second;
}
if ((temp.first)->left) {
qt.push(make_pair(
temp.first->left,
2 * temp.second));
}
if (temp.first->right) {
qt.push(make_pair(
temp.first->right,
2 * temp.second + 1));
}
count--;
if (count == 0) {
if (b - a + 1 == k)
return level;
pair<Node*, int > secondLabel = qt.front();
a = secondLabel.second;
level += 1;
count = qt.size();
}
}
return -1;
}
int main()
{
Node* 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);
int k = 4;
cout << findLevel(root, k, 1) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
static class Node
{
int data;
Node left, right;
};
static class pair
{
Node first;
int second;
pair(Node first, int second)
{
this .first = first;
this .second = second;
}
}
static Node newNode( int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null ;
return temp;
}
static int findLevel(Node root,
int k, int level)
{
Queue<pair> qt = new LinkedList<>();
qt.add( new pair(root, 0 ));
int count = 1 , b = 0 , a = 0 ;
while (!qt.isEmpty())
{
pair temp = qt.peek();
qt.poll();
if (count == 1 )
{
b = temp.second;
}
if (temp.first.left != null )
{
qt.add( new pair(
temp.first.left,
2 * temp.second));
}
if (temp.first.right != null )
{
qt.add( new pair(
temp.first.right,
2 * temp.second + 1 ));
}
count--;
if (count == 0 )
{
if ((b - a + 1 ) == k)
return level;
pair secondLabel = qt.peek();
a = secondLabel.second;
level += 1 ;
count = qt.size();
}
}
return - 1 ;
}
public static void main(String[] args)
{
Node 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 );
int k = 4 ;
System.out.println(findLevel(root, k, 1 ));
}
}
|
Python3
from collections import deque
class Node:
def __init__( self , key):
self .key = key
self .left = None
self .right = None
def findLevel(root: Node,
k: int , level: int ) - > int :
qt = deque()
qt.append([root, 0 ])
count = 1
b = 0
a = 0
while qt:
temp = qt.popleft()
if (count = = 1 ):
b = temp[ 1 ]
if (temp[ 0 ].left):
qt.append([temp[ 0 ].left,
2 * temp[ 1 ]])
if (temp[ 0 ].right):
qt.append([temp[ 0 ].right,
2 * temp[ 1 ] + 1 ])
count - = 1
if (count = = 0 ):
if (b - a + 1 = = k):
return level
secondLabel = qt[ 0 ]
a = secondLabel[ 1 ]
level + = 1
count = len (qt)
return - 1
if __name__ = = "__main__" :
root = Node( 5 )
root.left = Node( 6 )
root.right = Node( 2 )
root.right.right = Node( 8 )
root.left.left = Node( 7 )
root.left.left.left = Node( 5 )
root.left.right = Node( 3 )
root.left.right.right = Node( 4 )
k = 4
print (findLevel(root, k, 1 ))
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class GFG{
class Node
{
public int data;
public Node left, right;
};
class pair
{
public Node first;
public int second;
public pair(Node first, int second)
{
this .first = first;
this .second = second;
}
}
static Node newNode( int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null ;
return temp;
}
static int findLevel(Node root,
int k, int level)
{
Queue qt = new Queue();
qt.Enqueue( new pair(root, 0));
int count = 1, b = 0, a = 0;
while (qt.Count!=0)
{
pair temp = (pair)qt.Dequeue();
if (count == 1)
{
b = temp.second;
}
if (temp.first.left != null )
{
qt.Enqueue( new pair(
temp.first.left,
2 * temp.second));
}
if (temp.first.right != null )
{
qt.Enqueue( new pair(
temp.first.right,
2 * temp.second + 1));
}
count--;
if (count == 0)
{
if ((b - a + 1) == k)
return level;
pair secondLabel = (pair)qt.Peek();
a = secondLabel.second;
level += 1;
count = qt.Count;
}
}
return -1;
}
public static void Main( string [] args)
{
Node 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);
int k = 4;
Console.Write(findLevel(root, k, 1));
}
}
|
Javascript
<script>
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));
</script>
|
Time Complexity : O(N)
Auxiliary Space : O(N)
Share your thoughts in the comments
Please Login to comment...