Find the level with maximum setbit count in given Binary Tree
Last Updated :
05 Jul, 2022
Given a binary tree having N nodes, the task is to find the level having the maximum number of setbits.
Note: If two levels have same number of setbits print the one which has less no of nodes. If nodes are equal print the first level from top to bottom
Examples:
Input:
2
/ \
5 3
/ \
6 1
Output: 2
Explanation: Level 1 has only one setbit => 2 (010).
Level 2 has 4 setbits. => 5 (101) + 3 (011).
Level 3 has 3 setbits. => 6 (110) +1 (001).
Input:
2
/ \
5 3
/ \ \
6 1 8
Output: 2
Approach: The problem can be solved using level order traversal itself. Find the number of setbits in each level and the level having the maximum number of setbits following the given condition in the problem. Follow the steps mentioned below:
- Use the level order traversal and for each level:
- Find the total number of setbits in each level.
- Update the maximum setbits in a level and the level having the maximum number of setbits.
- Return the level with maximum setbits.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
int countSetBit( int x)
{
int c = 0;
while (x) {
int l = x % 10;
if (x & 1)
c++;
x /= 2;
}
return c;
}
void convert(Node* root)
{
if (!root)
return ;
root->data = countSetBit(root->data);
convert(root->left);
convert(root->right);
}
int printLevel(Node* root)
{
if (root == NULL)
return 0;
convert(root);
queue<Node*> q;
int currLevel = 0, ma = INT_MIN;
int prev = 0, ans = 0;
q.push(root);
while (q.empty() == false ) {
int size = q.size();
currLevel++;
int totalSet = 0, nodeCount = 0;
while (size--) {
Node* node = q.front();
totalSet += node->data;
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
nodeCount++;
}
if (ma < totalSet) {
ma = totalSet;
ans = currLevel;
}
else if (ma == totalSet && prev > nodeCount) {
ma = totalSet;
ans = currLevel;
prev = nodeCount;
}
prev = nodeCount;
}
return ans;
}
Node* newNode( int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
int main()
{
Node* root = newNode(2);
root->left = newNode(5);
root->right = newNode(3);
root->left->left = newNode(6);
root->left->right = newNode(1);
root->right->right = newNode(8);
cout << printLevel(root) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
static class Node {
int data;
Node left, right;
};
static int countSetBit( int x)
{
int c = 0 ;
while (x!= 0 ) {
int l = x % 10 ;
if (x% 2 == 1 )
c++;
x /= 2 ;
}
return c;
}
static void convert(Node root)
{
if (root== null )
return ;
root.data = countSetBit(root.data);
convert(root.left);
convert(root.right);
}
static int printLevel(Node root)
{
if (root == null )
return 0 ;
convert(root);
Queue<Node> q = new LinkedList<>();
int currLevel = 0 , ma = Integer.MIN_VALUE;
int prev = 0 , ans = 0 ;
q.add(root);
while (q.isEmpty() == false ) {
int size = q.size();
currLevel++;
int totalSet = 0 , nodeCount = 0 ;
while (size-- > 0 ) {
Node node = q.peek();
totalSet += node.data;
q.remove();
if (node.left != null )
q.add(node.left);
if (node.right != null )
q.add(node.right);
nodeCount++;
}
if (ma < totalSet) {
ma = totalSet;
ans = currLevel;
}
else if (ma == totalSet && prev > nodeCount) {
ma = totalSet;
ans = currLevel;
prev = nodeCount;
}
prev = nodeCount;
}
return ans;
}
static Node newNode( int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null ;
return temp;
}
public static void main(String[] args)
{
Node root = newNode( 2 );
root.left = newNode( 5 );
root.right = newNode( 3 );
root.left.left = newNode( 6 );
root.left.right = newNode( 1 );
root.right.right = newNode( 8 );
System.out.print(printLevel(root) + "\n" );
}
}
|
Python3
import sys
class Node:
def __init__( self ,d):
self .data = d
self .left = None
self .right = None
def countSetBit(x):
c = 0
while (x):
l = x % 10
if (x & 1 ):
c + = 1
x = (x / / 2 )
return c
def convert(root):
if (root = = None ):
return
root.data = countSetBit(root.data)
convert(root.left)
convert(root.right)
def printLevel(root):
if (root = = None ):
return 0
convert(root)
q = []
currLevel,ma = 0 , - sys.maxsize - 1
prev,ans = 0 , 0
q.append(root)
while ( len (q) ! = 0 ):
size = len (q)
currLevel + = 1
totalSet,nodeCount = 0 , 0
while (size):
node = q[ 0 ]
q = q[ 1 :]
totalSet + = node.data
if (node.left ! = None ):
q.append(node.left)
if (node.right ! = None ):
q.append(node.right)
nodeCount + = 1
size - = 1
if (ma < totalSet):
ma = totalSet
ans = currLevel
elif (ma = = totalSet and prev > nodeCount):
ma = totalSet
ans = currLevel
prev = nodeCount
prev = nodeCount
return ans
root = Node( 2 )
root.left = Node( 5 )
root.right = Node( 3 )
root.left.left = Node( 6 )
root.left.right = Node( 1 )
root.right.right = Node( 8 )
print (printLevel(root))
|
C#
using System;
using System.Collections.Generic;
public class GFG{
class Node {
public int data;
public Node left, right;
};
static int countSetBit( int x)
{
int c = 0;
while (x!=0) {
int l = x % 10;
if (x%2==1)
c++;
x /= 2;
}
return c;
}
static void convert(Node root)
{
if (root== null )
return ;
root.data = countSetBit(root.data);
convert(root.left);
convert(root.right);
}
static int printLevel(Node root)
{
if (root == null )
return 0;
convert(root);
Queue<Node> q = new Queue<Node>();
int currLevel = 0, ma = int .MinValue;
int prev = 0, ans = 0;
q.Enqueue(root);
while (q.Count!=0 ) {
int size = q.Count;
currLevel++;
int totalSet = 0, nodeCount = 0;
while (size-- >0) {
Node node = q.Peek();
totalSet += node.data;
q.Dequeue();
if (node.left != null )
q.Enqueue(node.left);
if (node.right != null )
q.Enqueue(node.right);
nodeCount++;
}
if (ma < totalSet) {
ma = totalSet;
ans = currLevel;
}
else if (ma == totalSet && prev > nodeCount) {
ma = totalSet;
ans = currLevel;
prev = nodeCount;
}
prev = nodeCount;
}
return ans;
}
static Node newNode( int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null ;
return temp;
}
public static void Main(String[] args)
{
Node root = newNode(2);
root.left = newNode(5);
root.right = newNode(3);
root.left.left = newNode(6);
root.left.right = newNode(1);
root.right.right = newNode(8);
Console.Write(printLevel(root) + "\n" );
}
}
|
Javascript
<script>
class Node {
constructor(d) {
this .data = d;
this .left = null ;
this .right = null ;
}
};
function countSetBit(x) {
let c = 0;
while (x) {
let l = x % 10;
if (x & 1)
c++;
x = Math.floor(x / 2);
}
return c;
}
function convert(root) {
if (root == null )
return ;
root.data = countSetBit(root.data);
convert(root.left);
convert(root.right);
}
function printLevel(root) {
if (root == null )
return 0;
convert(root);
let q = [];
let currLevel = 0, ma = Number.MIN_VALUE;
let prev = 0, ans = 0;
q.push(root);
while (q.length != 0) {
let size = q.length;
currLevel++;
let totalSet = 0, nodeCount = 0;
while (size--) {
let node = q.shift();
totalSet += node.data;
q.pop();
if (node.left != null )
q.push(node.left);
if (node.right != null )
q.push(node.right);
nodeCount++;
}
if (ma < totalSet) {
ma = totalSet;
ans = currLevel;
}
else if (ma == totalSet && prev > nodeCount) {
ma = totalSet;
ans = currLevel;
prev = nodeCount;
}
prev = nodeCount;
}
return ans;
}
let root = new Node(2);
root.left = new Node(5);
root.right = new Node(3);
root.left.left = new Node(6);
root.left.right = new Node(1);
root.right.right = new Node(8);
document.write(printLevel(root) + '<br>' );
</script>
|
Time Complexity: (N * D) where D is no of bit an element have
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...