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 Level wise positions of given node in a given Binary Tree
Next article icon

Count levels in a Binary Tree consisting of node values having set bits at different positions

Last Updated : 17 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Tree consisting of N nodes, the task is to count the number of levels in a Binary Tree such that the set bits of all the node values at the same level is at different positions.

Examples: 

Input: 

                      5               / \              6   9             / \   \            1   4   7

Output: 2 
Explanation: 
Level 1 has only 5 (= (101)2). 
Level 2 has 6 (= (0110)2) and 9 (= (1001)2). All set bits are at unique positions. 
Level 3 has 1 (0001)2, 4 (0100)2 and 7(0111)2. Therefore, 0th bit of node values 5 and 7 are set.

Input:  

               1            / \           2   3          / \   \         5   4   7

Output: 1

Naive Approach: The simplest approach to solve this problem to traverse the binary tree using level order traversal and at each level of the tree store the set bits of all the nodes using Map. Traverse the map and check if the frequency of set-bit at the same position is less than or equal to 1 or not. If found to be true, then increment the count. Finally, print the count obtained. 

Time Complexity: O(N) 
Auxiliary Space: O(32)

Efficient Approach: The above approach can be optimized based on the following observations:

If all the set bits of two numbers A and B are at different positions 
A XOR B = A OR B

Follow the steps below to solve the problem:

  • Initialize a variable, say prefiX_XOR, to store the prefix XOR of all the nodes at each level.
  • Initialize a variable, say prefiX_OR, to store the prefix OR of all the nodes at each level.
  • Traverse the binary tree using level order traversal. At every ith level, check if prefix_XOR ^ nodes is equal to (prefix_OR | nodes) or not. If found to be true for all the nodes at current level, then increment the count.
  • Finally, print the count obtained.

Below is the implementation of the above approach:

C++14
// C++ program for the above approach #include <bits/stdc++.h>  using namespace std;  // Structure of a node in // the binary tree struct TreeNode {   int val = 0;   TreeNode *left,*right;   TreeNode(int x)   {         val = x;         left = NULL;         right = NULL;   } };  // Function to find total unique levels void uniqueLevels(TreeNode *root) {      // Stores count of levels, where the set     // bits of all the nodes are at     // different positions     int uniqueLevels = 0;      // Store nodes at  each level of     // the tree using BFS     queue<TreeNode*> que;     que.push(root);      // Performing level order traversal     while (que.size() > 0)     {          // Stores count of nodes at         // current level         int length = que.size();          // Stores prefix XOR of all         // the nodes at current level         int prefix_XOR = 0;          // Stores prefix OR of all         // the nodes at current level         int prefix_OR = 0;          // Check if set bit of all the nodes         // at current level is at different         // positions or not         bool flag = true;          // Traverse nodes at current level         for(int i = 0; i < length; i++){              // Stores front element             // of the que             TreeNode *temp = que.front();             que.pop();              // Update prefix_OR             prefix_OR |= temp->val;              // Update prefix_XOR             prefix_XOR ^= temp->val;             if (prefix_XOR != prefix_OR)                 flag = false;              // If left subtree not NULL             if (temp->left)                 que.push(temp->left);              // If right subtree not NULL             if (temp->right)                 que.push(temp->right);              // Update length         }          //If bitwise AND is zero         if (flag)             uniqueLevels += 1;       }     cout << uniqueLevels; }  // Driver Code int main() {   TreeNode *root = new TreeNode(5);   root->left = new TreeNode(6);   root->right = new TreeNode(9);   root->left->left = new TreeNode(1);   root->left->right = new TreeNode(4);   root->right->right = new TreeNode(7);    // Function Call   uniqueLevels(root);   return 0; }  // This code is contributed by mohit kumar 29. 
Java
// Java program for the above approach import java.util.*; class GFG {    // Structure of a node in   // the binary tree   static class TreeNode   {     int val = 0;     TreeNode left, right;     TreeNode(int x)     {       val = x;       left = null;       right = null;     }   };    // Function to find total unique levels   static void uniqueLevels(TreeNode root)   {      // Stores count of levels, where the set     // bits of all the nodes are at     // different positions     int uniqueLevels = 0;      // Store nodes at  each level of     // the tree using BFS     Queue<TreeNode> que = new LinkedList<>();     que.add(root);      // Performing level order traversal     while (que.size() > 0)     {        // Stores count of nodes at       // current level       int length = que.size();        // Stores prefix XOR of all       // the nodes at current level       int prefix_XOR = 0;        // Stores prefix OR of all       // the nodes at current level       int prefix_OR = 0;        // Check if set bit of all the nodes       // at current level is at different       // positions or not       boolean flag = true;        // Traverse nodes at current level       for(int i = 0; i < length; i++)       {          // Stores front element         // of the que         TreeNode temp = que.peek();         que.remove();          // Update prefix_OR         prefix_OR |= temp.val;          // Update prefix_XOR         prefix_XOR ^= temp.val;         if (prefix_XOR != prefix_OR)           flag = false;          // If left subtree not null         if (temp.left != null)           que.add(temp.left);          // If right subtree not null         if (temp.right != null)           que.add(temp.right);          // Update length       }        //If bitwise AND is zero       if (flag)         uniqueLevels += 1;     }     System.out.print(uniqueLevels);   }    // Driver Code   public static void main(String[] args)   {     TreeNode root = new TreeNode(5);     root.left = new TreeNode(6);     root.right = new TreeNode(9);     root.left.left = new TreeNode(1);     root.left.right = new TreeNode(4);     root.right.right = new TreeNode(7);      // Function Call     uniqueLevels(root);   } }  // This code is contributed by 29AjayKumar  
Python3
# Python program for the above approach   # Structure of a node in # the binary tree class TreeNode:     def __init__(self, val = 0, left = None, right = None):         self.val = val         self.left = left         self.right = right  # Function to find total unique levels def uniqueLevels(root):      # Stores count of levels, where the set     # bits of all the nodes are at      # different positions      uniqueLevels = 0      # Store nodes at  each level of      # the tree using BFS     que = [root]      # Performing level order traversal     while len(que):              # Stores count of nodes at         # current level         length = len(que)          # Stores prefix XOR of all          # the nodes at current level         prefix_XOR = 0;          # Stores prefix OR of all          # the nodes at current level         prefix_OR = 0          # Check if set bit of all the nodes          # at current level is at different         # positions or not         flag = True          # Traverse nodes at current level         while length:              # Stores front element             # of the que             temp = que.pop(0)              # Update prefix_OR             prefix_OR |= temp.val              # Update prefix_XOR             prefix_XOR ^= temp.val              if prefix_XOR != prefix_OR:                 flag = False                          # If left subtree not NULL             if temp.left:                 que.append(temp.left)              # If right subtree not NULL                 if temp.right:                 que.append(temp.right)              # Update length                 length -= 1          # If bitwise AND is zero         if flag:             uniqueLevels += 1      print(uniqueLevels)  # Driver Code if __name__ == '__main__':          root = TreeNode(5)     root.left = TreeNode(6)     root.right = TreeNode(9)     root.left.left = TreeNode(1)     root.left.right = TreeNode(4)     root.right.right = TreeNode(7)      # Function Call     uniqueLevels(root) 
C#
// C# program for the above approach using System; using System.Collections.Generic; public class GFG {    // Structure of a node in   // the binary tree   class TreeNode   {     public int val = 0;     public TreeNode left, right;     public TreeNode(int x)     {       val = x;       left = null;       right = null;     }   };    // Function to find total unique levels   static void uniqueLevels(TreeNode root)   {      // Stores count of levels, where the set     // bits of all the nodes are at     // different positions     int uniqueLevels = 0;      // Store nodes at  each level of     // the tree using BFS     Queue<TreeNode> que = new Queue<TreeNode>();     que.Enqueue(root);      // Performing level order traversal     while (que.Count > 0)     {        // Stores count of nodes at       // current level       int length = que.Count;        // Stores prefix XOR of all       // the nodes at current level       int prefix_XOR = 0;        // Stores prefix OR of all       // the nodes at current level       int prefix_OR = 0;        // Check if set bit of all the nodes       // at current level is at different       // positions or not       bool flag = true;        // Traverse nodes at current level       for(int i = 0; i < length; i++)       {          // Stores front element         // of the que         TreeNode temp = que.Peek();         que.Dequeue();          // Update prefix_OR         prefix_OR |= temp.val;          // Update prefix_XOR         prefix_XOR ^= temp.val;         if (prefix_XOR != prefix_OR)           flag = false;          // If left subtree not null         if (temp.left != null)           que.Enqueue(temp.left);          // If right subtree not null         if (temp.right != null)           que.Enqueue(temp.right);          // Update length       }        //If bitwise AND is zero       if (flag)         uniqueLevels += 1;     }     Console.Write(uniqueLevels);   }    // Driver Code   public static void Main(String[] args)   {     TreeNode root = new TreeNode(5);     root.left = new TreeNode(6);     root.right = new TreeNode(9);     root.left.left = new TreeNode(1);     root.left.right = new TreeNode(4);     root.right.right = new TreeNode(7);      // Function Call     uniqueLevels(root);   } }  // This code is contributed by 29AjayKumar 
JavaScript
<script>  // Javascript program for the above approach  // Structure of a node in // the binary tree class TreeNode {     constructor(x)     {         this.val = x;         this.left = null;           this.right = null;     } }  // Function to find total unique levels function uniqueLevels(root) {          // Stores count of levels, where the set     // bits of all the nodes are at     // different positions     let uniqueLevels = 0;       // Store nodes at  each level of     // the tree using BFS     let que = [];     que.push(root);       // Performing level order traversal     while (que.length > 0)     {                  // Stores count of nodes at         // current level         let length = que.length;                  // Stores prefix XOR of all         // the nodes at current level         let prefix_XOR = 0;                  // Stores prefix OR of all         // the nodes at current level         let prefix_OR = 0;                  // Check if set bit of all the nodes         // at current level is at different         // positions or not         let flag = true;                  // Traverse nodes at current level         for(let i = 0; i < length; i++)         {                      // Stores front element             // of the que             let temp = que[0];             que.shift();                          // Update prefix_OR             prefix_OR |= temp.val;                          // Update prefix_XOR             prefix_XOR ^= temp.val;             if (prefix_XOR != prefix_OR)                 flag = false;                          // If left subtree not null             if (temp.left != null)                 que.push(temp.left);                          // If right subtree not null             if (temp.right != null)                 que.push(temp.right);         }                  // If bitwise AND is zero         if (flag)             uniqueLevels += 1;     }     document.write(uniqueLevels); }  // Driver Code let root = new TreeNode(5); root.left = new TreeNode(6); root.right = new TreeNode(9); root.left.left = new TreeNode(1); root.left.right = new TreeNode(4); root.right.right = new TreeNode(7);  // Function Call uniqueLevels(root);  // This code is contributed by unknown2108  </script> 

Output: 
2

 

Time Complexity: O(N) 
Auxiliary Space: O(N)


Next Article
Find Level wise positions of given node in a given Binary Tree
author
rohitsingh07052
Improve
Article Tags :
  • Bit Magic
  • Tree
  • Queue
  • Hash
  • DSA
  • Binary Tree
  • tree-level-order
  • Bitwise-AND
Practice Tags :
  • Bit Magic
  • Hash
  • Queue
  • Tree

Similar Reads

  • Count levels in a Binary Tree consisting of nodes valued 1 grouped together
    Given a Binary Tree consisting of 0s and 1s only, the task is to print the count of levels in the Binary Tree in which all the 1s are placed consecutively in a single group. Examples: Input: 0 / \ 1 0 / \ / \ 1 0 1 0 Output: 2 Explanation: In Levels 1 and 2, all the nodes with value 1 are placed con
    10 min read
  • Convert a Binary Tree to BST by left shifting digits of node values
    Given a Binary Tree of positive integers. The task is to convert it to a BST using left shift operations on the digits of the nodes. If it is not possible to convert the binary tree to BST then print -1. Examples: Input: 443 / \ 132 543 / \ 343 237 Output: 344 / \ 132 435 / \ 433 723 Explanation: 44
    12 min read
  • Find Level wise positions of given node in a given Binary Tree
    Given a binary tree and an integer X, the task is to find out all the occurrences of X in the given tree, and print its level and its position from left to right on that level. If X is not found, print -1. Examples: Input: X=35 10 / \ 20 30 / \ / \40 60 35 50Output: [(3, 3)]Explanation: Integer X=35
    7 min read
  • Count paths in a Binary Tree consisting of nodes in non-decreasing order
    Given a Binary Tree consisting of N nodes, the task is to find the number of paths from the root to any node X, such that all the node values in that path are at most X. Examples: Input: Below is the given Tree: Output: 4Explanation: The paths from the root to any node X that have value at most valu
    15 min read
  • Left rotate digits of node values of all levels of a Binary Tree in increasing order
    Given a Binary Tree, the task is to modify the Tree by left rotating every node any number of times such that every level consists of node values in increasing order from left to right. If it is not possible to arrange node values of any level in increasing order, then print "-1". Examples: Input: 3
    14 min read
  • Count of subtrees in a Binary Tree having bitwise OR value K
    Given a value K and a binary tree, the task is to find out the number of subtrees having bitwise OR of all its elements equal to K. Examples: Input: K = 5, Tree = 2 / \ 1 1 / \ \ 10 5 4 Output: 2 Explanation: Subtree 1: 5 It has only one element i.e. 5. So bitwise OR of subtree = 5 Subtree 2: 1 \ 4
    8 min read
  • Sum of decimal equivalents of binary node values in each level of a Binary Tree
    Given a Binary Tree consisting of nodes with values 0 and 1 only, the task is to find the total sum of the decimal equivalents of the binary numbers formed by connecting nodes at the same level from left to right, on each level. Examples: Input: Below is the given Tree: 0 / \ 1 0 / \ / \ 0 1 1 1Outp
    15 min read
  • Count diagonal paths from a node to a leaf consisting of same valued nodes
    Given a Binary Tree, the task is to find the count of diagonal paths to the leaf of a binary tree such that values of all the nodes on the same diagonal are equal. Examples: Input: 5 / \ 6 5 \ \ 6 5 Output: 2 Explanation: Diagonal 6 - 6 and 5 - 5 contains equal value. Therefore, the required output
    8 min read
  • Count of Root to Leaf Paths consisting of at most M consecutive Nodes having value K
    Given an Acyclic Undirected Graph in the form of a Binary Tree with the root at vertex 1 and values at each vertex [1, N] denoted by the array arr[], the task is to find the number of root to leaf paths that contain at most m consecutive nodes with value K. Example: Input: arr[] = {1, 0, 1, 0, 0, 1,
    8 min read
  • Print the nodes corresponding to the level value for each level of a Binary Tree
    Given a Binary Tree, the task for each level L is to print the Lth node of the tree. If the Lth node is not present for any level, print -1. Note: Consider the root node to be at the level 1 of the binary tree. Examples: Input: Below is the given Tree: Output:Level 1: 1Level 2: 3 Level 3: 6Level 4:
    15 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