Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Find the maximum node at a given level in a binary tree
Next article icon

Find the level with maximum setbit count in given Binary Tree

Last Updated : 05 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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>
 
 
Output
2

Time Complexity: (N * D) where D is no of bit an element have
Auxiliary Space: O(N)



Next Article
Find the maximum node at a given level in a binary tree
author
nobita04
Improve
Article Tags :
  • Bit Magic
  • DSA
  • Geeks Premier League
  • Mathematical
  • Searching
  • Tree
  • Binary Tree
  • Geeks-Premier-League-2022
  • setBitCount
  • tree-level-order
Practice Tags :
  • Bit Magic
  • Mathematical
  • Searching
  • Tree

Similar Reads

  • Find the maximum node at a given level in a binary tree
    Given a Binary Tree and a Level. The task is to find the node with the maximum value at that given level. The idea is to traverse the tree along depth recursively and return the nodes once the required level is reached and then return the maximum of left and right subtrees for each subsequent call.
    13 min read
  • Find maximum level sum in Binary Tree
    Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum level in it. Examples: Input : 4 / \ 2 -5 / \ /\ -1 3 -2 6Output: 6Explanation :Sum of all nodes of 0'th level is 4Sum of all nodes of 1'th level is -3Sum of all nodes of 0'th level is 6Hence maximum sum is 6
    15+ min read
  • Find maximum level product in Binary Tree
    Given a Binary Tree having positive and negative nodes, the task is to find maximum product level in it. Examples: Input : 4 / \ 2 -5 / \ /\ -1 3 -2 6 Output: 36 Explanation : Product of all nodes of 0'th level is 4 Product of all nodes of 1'th level is -10 Product of all nodes of 2'th level is 36 H
    9 min read
  • Find the largest Complete Subtree in a given Binary Tree
    Given a Binary Tree, the task is to find the size and also the inorder traversal of the largest Complete sub-tree in the given Binary Tree. Complete Binary Tree - A Binary tree is a Complete Binary Tree if all levels are filled except possibly the last level and the last level has all keys as left a
    13 min read
  • Find Maximum Level Sum in Binary Tree using Recursion
    Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum level in it and print the maximum sum.Examples: Input: 4 / \ 2 -5 / \ / \ -1 3 -2 6 Output: 6 Sum of all nodes of the 1st level is 4. Sum of all nodes of the 2nd level is -3. Sum of all nodes of the 3rd level
    10 min read
  • Find the parent node of maximum product Siblings in given Binary Tree
    Given a binary tree, the task is to find the node whose children have maximum Sibling product in the given Binary Tree. If there are multiple such nodes, return the node which has the maximum value. Examples: Input: Tree: 4 / \ 5 2 / \ 3 1 / \6 12Output: 3Explanation: For the above tree, the maximum
    15+ min read
  • Find element with the maximum set bits in an array
    Given an array arr[]. The task is to find an element from arr[] which has the maximum count of set bits.Examples: Input: arr[] = {10, 100, 1000, 10000} Output: 1000 Binary(10) = 1010 (2 set bits) Binary(100) = 1100100 (3 set bits) Binary(1000) = 1111101000 (6 set bits) Binary(10000) = 10011100010000
    5 min read
  • Finding Minimum Steps in Special Binary Tree
    Given two integer values (i and j) as input representing two nodes of a special binary tree. The special binary tree has this property that the root node's value is always 1 and for every node, its left child will be the node's value * 3, and the right child will be ( node's value * 3) + 1. The give
    8 min read
  • Find the largest Perfect Subtree in a given Binary Tree
    Given a Binary Tree, the task is to find the size of largest Perfect sub-tree in the given Binary Tree. Perfect Binary Tree - A Binary tree is Perfect Binary Tree in which all internal nodes have two children and all leaves are at the same level. Examples: Input: 1 / \ 2 3 / \ / 4 5 6 Output: Size :
    12 min read
  • Maximum Consecutive Increasing Path Length in Binary Tree
    Given a Binary Tree find the length of the longest path which comprises of nodes with consecutive values in increasing order. Every node is considered as a path of length 1. Examples: 10 / \ / \ 11 9 / \ /\ / \ / \ 13 12 13 8 Maximum Consecutive Path Length is 3 (10, 11, 12) Note: 10, 9 ,8 is NOT co
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences