Open In App

Count levels in a Binary Tree consisting of nodes valued 1 grouped together

Last Updated : 18 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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 consecutively.

Input:            0

                   /   \

                1     0

               /  \     \

             1   1       0

            / \   \      /   \

           1   1   1  0    0

Output: 4

Explanation: In all the levels, nodes with value 1 are placed consecutively.

Approach: Follow the steps below to solve the problem:

  • Perform Level Order Traversal using Queue.
  • Traverse each level of the Binary Tree and consider following three variables: 
    1. flag1: Sets to 1 after first occurrence of node with value 1.
    2. flag0: Sets to 1 after first occurrence of node with value 0 after occurrence of any node with value 1.
    3. flag2: Sets after first occurrence of node with value 1 after both flag0 and flag1 are set to 1.
  • After traversing each level, check if flag1 is set to 1 and flag2 is 0. If found to be true, include that level in the count.
  • Finally, print the count obtained.

Below is the implementation of the above approach:

C++




// C++ Program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// A Binary Tree Node
struct node {
 
    // Left Child
    struct node* left;
 
    int data;
 
    // Right Child
    struct node* right;
};
 
// Function to perform level order traversal
// count levels with all 1s grouped together
int countLevels(node* root)
{
    if (root == NULL)
        return 0;
 
    int Count = 0;
 
    // Create an empty queue for
    // level order traversal
    queue<node*> q;
 
    // Stores front element of the queue
    node* curr;
 
    // Enqueue root and NULL node
    q.push(root);
 
    // Stores Nodes of
    // Current Level
    while (!q.empty()) {
        int n = q.size();
 
        int flag0 = 0, flag1 = 0, flag2 = 0;
 
        while (n--) {
 
            // Stores first node of
            // the current level
            curr = q.front();
            q.pop();
 
            if (curr) {
 
                // If left child exists
                if (curr->left)
 
                    // Push into the Queue
                    q.push(curr->left);
 
                // If right child exists
                if (curr->right)
 
                    // Push into the Queue
                    q.push(curr->right);
 
                if (curr->data == 1) {
 
                    // If current node is the first
                    // node with value 1
                    if (!flag1)
                        flag1 = 1;
 
                    // If current node has value 1
                    // after occurrence of nodes
                    // with value 0 following a
                    // sequence of nodes with value 1
                    if (flag1 && flag0)
                        flag2 = 1;
                }
 
                // If current node is the first node
                // with value 0 after a sequence
                // of nodes with value 1
                if (curr->data == 0 && flag1)
                    flag0 = 1;
            }
        }
 
        if (flag1 && !flag2)
            Count++;
    }
 
    return Count;
}
 
// Function to create a Tree Node
node* newNode(int data)
{
    node* temp = new node;
    temp->data = data;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}
 
// Driver Code
int main()
{
    node* root = newNode(0);
    root->left = newNode(0);
    root->right = newNode(1);
    root->left->left = newNode(0);
    root->left->right = newNode(1);
    root->right->left = newNode(1);
    root->right->right = newNode(0);
 
    cout << countLevels(root);
    return 0;
}


Java




// Java Program to implement
// the above approach
import java.util.*;
class GFG
{
 
// A Binary Tree Node
static class node
{
 
    // Left Child
    node left;
    int data;
 
    // Right Child
    node right;
};
 
// Function to perform level order traversal
// count levels with all 1s grouped together
static int countLevels(node root)
{
    if (root == null)
        return 0;
    int Count = 0;
 
    // Create an empty queue for
    // level order traversal
    Queue<node> q = new LinkedList<>();
 
    // Stores front element of the queue
    node curr;
 
    // Enqueue root and null node
    q.add(root);
 
    // Stores Nodes of
    // Current Level
    while (!q.isEmpty())
    {
        int n = q.size();
        int flag0 = 0, flag1 = 0, flag2 = 0;
        while (n-- >0)
        {
 
            // Stores first node of
            // the current level
            curr = q.peek();
            q.remove();
            if (curr != null)
            {
 
                // If left child exists
                if (curr.left != null)
 
                    // Push into the Queue
                    q.add(curr.left);
 
                // If right child exists
                if (curr.right != null)
 
                    // Push into the Queue
                    q.add(curr.right);
 
                if (curr.data == 1)
                {
 
                    // If current node is the first
                    // node with value 1
                    if (flag1 == 0)
                        flag1 = 1;
 
                    // If current node has value 1
                    // after occurrence of nodes
                    // with value 0 following a
                    // sequence of nodes with value 1
                    if (flag1 > 0 && flag0 > 0)
                        flag2 = 1;
                }
 
                // If current node is the first node
                // with value 0 after a sequence
                // of nodes with value 1
                if (curr.data == 0 && flag1 > 0)
                    flag0 = 1;
            }
        }
 
        if (flag1 > 0 && flag2 == 0)
            Count++;
    }
    return Count;
}
 
// Function to create a Tree Node
static node newNode(int data)
{
    node temp = new node();
    temp.data = data;
    temp.left = null;
    temp.right = null;
    return temp;
}
 
// Driver Code
public static void main(String[] args)
{
    node root = newNode(0);
    root.left = newNode(0);
    root.right = newNode(1);
    root.left.left = newNode(0);
    root.left.right = newNode(1);
    root.right.left = newNode(1);
    root.right.right = newNode(0);
    System.out.print(countLevels(root));
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program to implement
# the above approach
from collections import deque
 
# A Binary Tree Node
class node:
     
    def __init__(self):
         
        # Left Child
        self.left = None
 
        self.data = 0
 
        # Right Child
        self.right = None
 
# Function to perform level order traversal
# count levels with all 1s grouped together
def countLevels(root):
 
    if (root == None):
        return 0
 
    Count = 0
 
    # Create an empty queue for
    # level order traversal
    q = deque()
 
    # Stores front element of the queue
    curr = node()
 
    # Enqueue root and None node
    q.append(root)
 
    # Stores Nodes of
    # Current Level
    while q:
        n = len(q)
        flag0 = 0
        flag1 = 0
        flag2 = 0
 
        while (n):
 
            # Stores first node of
            # the current level
            curr = q[0]
            q.popleft()
 
            if (curr):
 
                # If left child exists
                if (curr.left):
 
                    # Push into the Queue
                    q.append(curr.left)
 
                # If right child exists
                if (curr.right):
 
                    # Push into the Queue
                    q.append(curr.right)
 
                if (curr.data == 1):
 
                    # If current node is the first
                    # node with value 1
                    if (not flag1):
                        flag1 = 1
 
                    # If current node has value 1
                    # after occurrence of nodes
                    # with value 0 following a
                    # sequence of nodes with value 1
                    if (flag1 and flag0):
                        flag2 = 1
 
                # If current node is the first node
                # with value 0 after a sequence
                # of nodes with value 1
                if (curr.data == 0 and flag1):
                    flag0 = 1
 
            n -= 1
 
        if (flag1 and not flag2):
            Count += 1
 
    return Count
 
# Function to create a Tree Node
def newNode(data):
 
    temp = node()
    temp.data = data
    temp.left = None
    temp.right = None
    return temp
 
# Driver Code
if __name__ == "__main__":
 
    root = newNode(0)
    root.left = newNode(0)
    root.right = newNode(1)
    root.left.left = newNode(0)
    root.left.right = newNode(1)
    root.right.left = newNode(1)
    root.right.right = newNode(0)
 
    print(countLevels(root))
 
# This code is contributed by sanjeev2552


C#




// C# Program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
// A Binary Tree Node
class node
{
 
    // Left Child
    public node left;
    public int data;
 
    // Right Child
    public node right;
};
 
// Function to perform level order traversal
// count levels with all 1s grouped together
static int countLevels(node root)
{
    if (root == null)
        return 0;
    int Count = 0;
 
    // Create an empty queue for
    // level order traversal
    Queue<node> q = new Queue<node>();
 
    // Stores front element of the queue
    node curr;
 
    // Enqueue root and null node
    q.Enqueue(root);
 
    // Stores Nodes of
    // Current Level
    while (q.Count != 0)
    {
        int n = q.Count;
        int flag0 = 0, flag1 = 0, flag2 = 0;
        while (n-- >0)
        {
 
            // Stores first node of
            // the current level
            curr = q.Peek();
            q.Dequeue();
            if (curr != null)
            {
 
                // If left child exists
                if (curr.left != null)
 
                    // Push into the Queue
                    q.Enqueue(curr.left);
 
                // If right child exists
                if (curr.right != null)
 
                    // Push into the Queue
                    q.Enqueue(curr.right);
 
                if (curr.data == 1)
                {
 
                    // If current node is the first
                    // node with value 1
                    if (flag1 == 0)
                        flag1 = 1;
 
                    // If current node has value 1
                    // after occurrence of nodes
                    // with value 0 following a
                    // sequence of nodes with value 1
                    if (flag1 > 0 && flag0 > 0)
                        flag2 = 1;
                }
 
                // If current node is the first node
                // with value 0 after a sequence
                // of nodes with value 1
                if (curr.data == 0 && flag1 > 0)
                    flag0 = 1;
            }
        }
        if (flag1 > 0 && flag2 == 0)
            Count++;
    }
    return Count;
}
 
// Function to create a Tree Node
static node newNode(int data)
{
    node temp = new node();
    temp.data = data;
    temp.left = null;
    temp.right = null;
    return temp;
}
 
// Driver Code
public static void Main(String[] args)
{
    node root = newNode(0);
    root.left = newNode(0);
    root.right = newNode(1);
    root.left.left = newNode(0);
    root.left.right = newNode(1);
    root.right.left = newNode(1);
    root.right.right = newNode(0);
    Console.Write(countLevels(root));
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
  // JavaScript program for above approach
  
  // A Binary Tree Node
  class node
  {
      constructor(data) {
         this.left = null;
         this.right = null;
         this.data = data;
      }
  }
   
  // Function to create a Tree Node
  function newNode(data)
  {
      let temp = new node(data);
      return temp;
  }
   
  // Function to perform level order traversal
  // count levels with all 1s grouped together
  function countLevels(root)
  {
      if (root == null)
          return 0;
      let Count = 0;
    
      // Create an empty queue for
      // level order traversal
      let q = [];
    
      // Stores front element of the queue
      let curr;
    
      // Enqueue root and null node
      q.push(root);
    
      // Stores Nodes of
      // Current Level
      while (q.length > 0)
      {
          let n = q.length;
          let flag0 = 0, flag1 = 0, flag2 = 0;
          while (n-- >0)
          {
    
              // Stores first node of
              // the current level
              curr = q[0];
              q.shift();
              if (curr != null)
              {
    
                  // If left child exists
                  if (curr.left != null)
    
                      // Push into the Queue
                      q.push(curr.left);
    
                  // If right child exists
                  if (curr.right != null)
    
                      // Push into the Queue
                      q.push(curr.right);
    
                  if (curr.data == 1)
                  {
    
                      // If current node is the first
                      // node with value 1
                      if (flag1 == 0)
                          flag1 = 1;
    
                      // If current node has value 1
                      // after occurrence of nodes
                      // with value 0 following a
                      // sequence of nodes with value 1
                      if (flag1 > 0 && flag0 > 0)
                          flag2 = 1;
                  }
    
                  // If current node is the first node
                  // with value 0 after a sequence
                  // of nodes with value 1
                  if (curr.data == 0 && flag1 > 0)
                      flag0 = 1;
              }
          }
    
          if (flag1 > 0 && flag2 == 0)
              Count++;
      }
      return Count;
  }
   
  let root = newNode(0);
  root.left = newNode(0);
  root.right = newNode(1);
  root.left.left = newNode(0);
  root.left.right = newNode(1);
  root.right.left = newNode(1);
  root.right.right = newNode(0);
  document.write(countLevels(root));
     
</script>


Output: 

2

 

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



Similar Reads

Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
Given a Binary Tree, the task is for each level is to print the total number of nodes from all lower levels which are less than or equal to every node present at that level. Examples: Input: Below is the given tree: 4 / \ 3 5 / \ / \ 10 2 3 1 Output: 4 3 0Explanation:Nodes in level 1 has 4 nodes as (3) in level 2 and (2, 3, 1) in level 3. Nodes in
11 min read
Remove all subtrees consisting only of even valued nodes from a Binary Tree
Given a Binary Tree, the task is to remove all the subtrees that do not contain any odd valued node. Print the Levelorder Traversal of the tree after removal of these subtrees. Note: Print NULL for removed nodes. Examples: Input: Below is the given Tree: 1 \ 2 / \ 8 5Output: 1 NULL 2 NULL 5Explanation:Tree after pruning: 1 \ 2 \ 5 Input: Below is t
8 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 is 2. Input: 5 / \ 6 5 \ \ 5 5 Output: 1 Approach:
8 min read
Count levels in a Binary Tree consisting of node values having set bits at different positions
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
10 min read
Check if a path exists for a cell valued 1 to reach the bottom right corner of a Matrix before any cell valued 2
Given a matrix arr[][] of dimensions N * M, having elements 0, 1, and 2. There is only one cell with value 1 present in the matrix. The task is to check if it is possible for 1 to reach the bottom right corner before any cell valued 2 or not using the following operations: 2 can replicate itself 1 unit in all four directions in 1 unit of time.1 can
11 min read
Difference between sum of even and odd valued nodes in a Binary Tree
Given a binary tree, the task is to find the absolute difference between the even valued and the odd valued nodes in a binary tree. Examples: Input: 5 / \ 2 6 / \ \ 1 4 8 / / \ 3 7 9 Output: 5 Explanation: Sum of the odd value nodes is: 5 + 1 + 3 + 7 + 9 = 25 Sum of the even value nodes is: 2 + 6 + 4 + 8 = 20 Absolute difference = (25 – 20) = 5. In
10 min read
Maximize numbers that can be grouped together based on given conditions
Given a 2D array A[][] of size N x 2 where: Every element lies between [1, N].A[i][0] signifies that there must be at most A[i][0] elements strictly lesser than i+1 and at most A[i][1] elements strictly greater than i+1. The task is to find the maximum number of elements that can come together abiding by the above condition. Examples: Input: N = 3,
10 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 values of node X are: Node 3(root node): It always fol
15 min read
Print odd positioned nodes of odd levels in level order of the given binary tree
Given a binary tree, the task is to print the odd positioned nodes of odd levels in the level order traversal of the tree. The root is considered at level 0, and the leftmost node of any level is considered as a node at position 0.Example: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 / \ 10 11 Output: 3 9 Input: 2 / \ 4 15 / / 45 17 Output: 15 Prerequi
8 min read
Print all nodes between two given levels in Binary Tree
Given a binary tree, print all nodes between two given levels in a binary tree. Print the nodes level-wise, i.e., the nodes for any level should be printed from left to right. In the above tree, if the starting level is 2 and the ending level is 3 then the solution should print: 2 3 4 5 6 7 Note: Level number starts with 1. That is, the root node i
15 min read
Practice Tags :