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++
// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
// Structure of a binary tree node
struct Node {
int data;
struct Node *left, *right;
};
// Function to count no of set bit
int countSetBit(int x)
{
int c = 0;
while (x) {
int l = x % 10;
if (x & 1)
c++;
x /= 2;
}
return c;
}
// Function to convert tree element
// by count of set bit they have
void convert(Node* root)
{
if (!root)
return;
root->data = countSetBit(root->data);
convert(root->left);
convert(root->right);
}
// Function to get level with max set bit
int printLevel(Node* root)
{
// Base Case
if (root == NULL)
return 0;
// Replace tree elements by
// count of set bits they contain
convert(root);
// Create an empty queue
queue<Node*> q;
int currLevel = 0, ma = INT_MIN;
int prev = 0, ans = 0;
// Enqueue Root and initialize height
q.push(root);
// Loop to implement level order traversal
while (q.empty() == false) {
// Print front of queue and
// remove it from queue
int size = q.size();
currLevel++;
int totalSet = 0, nodeCount = 0;
while (size--) {
Node* node = q.front();
// Add all the set bit
// in the current level
totalSet += node->data;
q.pop();
// Enqueue left child
if (node->left != NULL)
q.push(node->left);
// Enqueue right child
if (node->right != NULL)
q.push(node->right);
// Count current level node
nodeCount++;
}
// Update the ans when needed
if (ma < totalSet) {
ma = totalSet;
ans = currLevel;
}
// If two level have same set bit
// one with less node become ans
else if (ma == totalSet && prev > nodeCount) {
ma = totalSet;
ans = currLevel;
prev = nodeCount;
}
// Assign prev =
// current level node count
// We can use it for further levels
// When 2 level have
// same set bit count
// print level with less node
prev = nodeCount;
}
return ans;
}
// Utility function to create new tree node
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program
int main()
{
// Binary tree as shown in example
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);
// Function call
cout << printLevel(root) << endl;
return 0;
}
Java
// Java code to implement the above approach
import java.util.*;
class GFG{
// Structure of a binary tree node
static class Node {
int data;
Node left, right;
};
// Function to count no of set bit
static int countSetBit(int x)
{
int c = 0;
while (x!=0) {
int l = x % 10;
if (x%2==1)
c++;
x /= 2;
}
return c;
}
// Function to convert tree element
// by count of set bit they have
static void convert(Node root)
{
if (root==null)
return;
root.data = countSetBit(root.data);
convert(root.left);
convert(root.right);
}
// Function to get level with max set bit
static int printLevel(Node root)
{
// Base Case
if (root == null)
return 0;
// Replace tree elements by
// count of set bits they contain
convert(root);
// Create an empty queue
Queue<Node> q = new LinkedList<>();
int currLevel = 0, ma = Integer.MIN_VALUE;
int prev = 0, ans = 0;
// Enqueue Root and initialize height
q.add(root);
// Loop to implement level order traversal
while (q.isEmpty() == false) {
// Print front of queue and
// remove it from queue
int size = q.size();
currLevel++;
int totalSet = 0, nodeCount = 0;
while (size-- >0) {
Node node = q.peek();
// Add all the set bit
// in the current level
totalSet += node.data;
q.remove();
// Enqueue left child
if (node.left != null)
q.add(node.left);
// Enqueue right child
if (node.right != null)
q.add(node.right);
// Count current level node
nodeCount++;
}
// Update the ans when needed
if (ma < totalSet) {
ma = totalSet;
ans = currLevel;
}
// If two level have same set bit
// one with less node become ans
else if (ma == totalSet && prev > nodeCount) {
ma = totalSet;
ans = currLevel;
prev = nodeCount;
}
// Assign prev =
// current level node count
// We can use it for further levels
// When 2 level have
// same set bit count
// print level with less node
prev = nodeCount;
}
return ans;
}
// Utility function to create new tree node
static Node newNode(int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null;
return temp;
}
// Driver program
public static void main(String[] args)
{
// Binary tree as shown in example
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);
// Function call
System.out.print(printLevel(root) +"\n");
}
}
// This code is contributed by shikhasingrajput
Python3
# Python code for the above approach
# Structure of a binary Tree node
import sys
class Node:
def __init__(self,d):
self.data = d
self.left = None
self.right = None
# Function to count no of set bit
def countSetBit(x):
c = 0
while (x):
l = x % 10
if (x & 1):
c += 1
x = (x // 2)
return c
# Function to convert tree element
# by count of set bit they have
def convert(root):
if (root == None):
return
root.data = countSetBit(root.data)
convert(root.left)
convert(root.right)
# Function to get level with max set bit
def printLevel(root):
# Base Case
if (root == None):
return 0
# Replace tree elements by
# count of set bits they contain
convert(root)
# Create an empty queue
q = []
currLevel,ma = 0, -sys.maxsize - 1
prev,ans = 0,0
# Enqueue Root and initialize height
q.append(root)
# Loop to implement level order traversal
while (len(q) != 0):
# Print front of queue and
# remove it from queue
size = len(q)
currLevel += 1
totalSet,nodeCount = 0,0
while (size):
node = q[0]
q = q[1:]
# Add all the set bit
# in the current level
totalSet += node.data
# Enqueue left child
if (node.left != None):
q.append(node.left)
# Enqueue right child
if (node.right != None):
q.append(node.right)
# Count current level node
nodeCount += 1
size -= 1
# Update the ans when needed
if (ma < totalSet):
ma = totalSet
ans = currLevel
# If two level have same set bit
# one with less node become ans
elif (ma == totalSet and prev > nodeCount):
ma = totalSet
ans = currLevel
prev = nodeCount
# Assign prev =
# current level node count
# We can use it for further levels
# When 2 level have
# same set bit count
# print level with less node
prev = nodeCount
return ans
# Driver program
# Binary tree as shown in example
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)
# Function call
print(printLevel(root))
# This code is contributed by shinjanpatra
C#
// C# code to implement the above approach
using System;
using System.Collections.Generic;
public class GFG{
// Structure of a binary tree node
class Node {
public int data;
public Node left, right;
};
// Function to count no of set bit
static int countSetBit(int x)
{
int c = 0;
while (x!=0) {
int l = x % 10;
if (x%2==1)
c++;
x /= 2;
}
return c;
}
// Function to convert tree element
// by count of set bit they have
static void convert(Node root)
{
if (root==null)
return;
root.data = countSetBit(root.data);
convert(root.left);
convert(root.right);
}
// Function to get level with max set bit
static int printLevel(Node root)
{
// Base Case
if (root == null)
return 0;
// Replace tree elements by
// count of set bits they contain
convert(root);
// Create an empty queue
Queue<Node> q = new Queue<Node>();
int currLevel = 0, ma = int.MinValue;
int prev = 0, ans = 0;
// Enqueue Root and initialize height
q.Enqueue(root);
// Loop to implement level order traversal
while (q.Count!=0 ) {
// Print front of queue and
// remove it from queue
int size = q.Count;
currLevel++;
int totalSet = 0, nodeCount = 0;
while (size-- >0) {
Node node = q.Peek();
// Add all the set bit
// in the current level
totalSet += node.data;
q.Dequeue();
// Enqueue left child
if (node.left != null)
q.Enqueue(node.left);
// Enqueue right child
if (node.right != null)
q.Enqueue(node.right);
// Count current level node
nodeCount++;
}
// Update the ans when needed
if (ma < totalSet) {
ma = totalSet;
ans = currLevel;
}
// If two level have same set bit
// one with less node become ans
else if (ma == totalSet && prev > nodeCount) {
ma = totalSet;
ans = currLevel;
prev = nodeCount;
}
// Assign prev =
// current level node count
// We can use it for further levels
// When 2 level have
// same set bit count
// print level with less node
prev = nodeCount;
}
return ans;
}
// Utility function to create new tree node
static Node newNode(int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null;
return temp;
}
// Driver program
public static void Main(String[] args)
{
// Binary tree as shown in example
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);
// Function call
Console.Write(printLevel(root) +"\n");
}
}
// This code contributed by shikhasingrajput
JavaScript
<script>
// JavaScript code for the above approach
// Structure of a binary Tree node
class Node {
constructor(d) {
this.data = d;
this.left = null;
this.right = null;
}
};
// Function to count no of set bit
function countSetBit(x) {
let c = 0;
while (x) {
let l = x % 10;
if (x & 1)
c++;
x = Math.floor(x / 2);
}
return c;
}
// Function to convert tree element
// by count of set bit they have
function convert(root) {
if (root == null)
return;
root.data = countSetBit(root.data);
convert(root.left);
convert(root.right);
}
// Function to get level with max set bit
function printLevel(root) {
// Base Case
if (root == null)
return 0;
// Replace tree elements by
// count of set bits they contain
convert(root);
// Create an empty queue
let q = [];
let currLevel = 0, ma = Number.MIN_VALUE;
let prev = 0, ans = 0;
// Enqueue Root and initialize height
q.push(root);
// Loop to implement level order traversal
while (q.length != 0) {
// Print front of queue and
// remove it from queue
let size = q.length;
currLevel++;
let totalSet = 0, nodeCount = 0;
while (size--) {
let node = q.shift();
// Add all the set bit
// in the current level
totalSet += node.data;
q.pop();
// Enqueue left child
if (node.left != null)
q.push(node.left);
// Enqueue right child
if (node.right != null)
q.push(node.right);
// Count current level node
nodeCount++;
}
// Update the ans when needed
if (ma < totalSet) {
ma = totalSet;
ans = currLevel;
}
// If two level have same set bit
// one with less node become ans
else if (ma == totalSet && prev > nodeCount) {
ma = totalSet;
ans = currLevel;
prev = nodeCount;
}
// Assign prev =
// current level node count
// We can use it for further levels
// When 2 level have
// same set bit count
// print level with less node
prev = nodeCount;
}
return ans;
}
// Driver program
// Binary tree as shown in example
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);
// Function call
document.write(printLevel(root) + '<br>');
// This code is contributed by Potta Lokesh
</script>
Time Complexity: (N * D) where D is no of bit an element have
Auxiliary Space: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read