Open In App

Count the number of nodes at given level in a tree using BFS.

Last Updated : 28 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a tree represented as an undirected graph. Count the number of nodes at a given level l. It may be assumed that vertex 0 is the root of the tree.

Examples: 

Input :   7
          0 1
          0 2
          1 3
          1 4 
          1 5
          2 6
          2
Output :  4

Input : 6
        0 1
        0 2
        1 3
        2 4
        2 5
        2
Output : 3

BFS is a traversing algorithm that starts traversing from a selected node (source or starting node) and traverses the graph layer-wise thus exploring the neighbour nodes (nodes that are directly connected to the source node). Then, move towards the next-level neighbor nodes. 

As the name BFS suggests, traverse the graph breadth wise as follows:

  1. First move horizontally and visit all the nodes of the current layer. 
  2. Move to the next layer.

In this code, while visiting each node, the level of that node is set with an increment in the level of its parent node i.e., level[child] = level[parent] + 1. This is how the level of each node is determined. The root node lies at level zero in the tree.

Explanation :

     0         Level 0
   /   \ 
  1     2      Level 1
/ |\    |
3 4 5   6      Level 2

Given a tree with 7 nodes and 6 edges in which node 0 lies at 0 level. Level of 1 can be updated as : level[1] = level[0] +1 as 0 is the parent node of 1. Similarly, the level of other nodes can be updated by adding 1 to the level of their parent. 

level[2] = level[0] + 1, i.e level[2] = 0 + 1 = 1. 
level[3] = level[1] + 1, i.e level[3] = 1 + 1 = 2. 
level[4] = level[1] + 1, i.e level[4] = 1 + 1 = 2. 
level[5] = level[1] + 1, i.e level[5] = 1 + 1 = 2. 
level[6] = level[2] + 1, i.e level[6] = 1 + 1 = 2.
Then, count of number of nodes which are at level l(i.e, l=2) is 4 (node:- 3, 4, 5, 6) 

Implementation:

C++




// C++ Program to print
// count of nodes
// at given level.
#include <iostream>
#include <list>
 
using namespace std;
 
// This class represents
// a directed graph
// using adjacency
// list representation
class Graph {
    // No. of vertices
    int V;
 
    // Pointer to an
    // array containing
    // adjacency lists
    list<int>* adj;
 
public:
    // Constructor
    Graph(int V);
 
    // function to add
    // an edge to graph
    void addEdge(int v, int w);
 
    // Returns count of nodes at
    // level l from given source.
    int BFS(int s, int l);
};
 
Graph::Graph(int V)
{
    this->V = V;
    adj = new list<int>[V];
}
 
void Graph::addEdge(int v, int w)
{
    // Add w to v’s list.
    adj[v].push_back(w);
 
    // Add v to w's list.
    adj[w].push_back(v);
}
 
int Graph::BFS(int s, int l)
{
    // Mark all the vertices
    // as not visited
    bool* visited = new bool[V];
    int level[V];
 
    for (int i = 0; i < V; i++) {
        visited[i] = false;
        level[i] = 0;
    }
 
    // Create a queue for BFS
    list<int> queue;
 
    // Mark the current node as
    // visited and enqueue it
    visited[s] = true;
    queue.push_back(s);
    level[s] = 0;
 
    while (!queue.empty()) {
 
        // Dequeue a vertex from
        // queue and print it
        s = queue.front();
        queue.pop_front();
 
        // Get all adjacent vertices
        // of the dequeued vertex s.
        // If a adjacent has not been
        // visited, then mark it
        // visited and enqueue it
        for (auto i = adj[s].begin();
                  i != adj[s].end(); ++i) {
            if (!visited[*i]) {
 
                // Setting the level
                // of each node with
                // an increment in the
                // level of parent node
                level[*i] = level[s] + 1;
                visited[*i] = true;
                queue.push_back(*i);
            }
        }
    }
 
    int count = 0;
    for (int i = 0; i < V; i++)
        if (level[i] == l)
            count++;   
    return count; 
}
 
// Driver program to test
// methods of graph class
int main()
{
    // Create a graph given
    // in the above diagram
    Graph g(6);
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 3);
    g.addEdge(2, 4);
    g.addEdge(2, 5);
 
    int level = 2;
 
    cout << g.BFS(0, level);
 
    return 0;
}


Java




// Java Program to print
// count of nodes
// at given level.
import java.util.*;
 
// This class represents
// a directed graph
// using adjacency
// list representation
class Graph
{
 
  // No. of vertices
  int V;
 
   
  Vector<Integer>[] adj;
 
  // Constructor
  @SuppressWarnings("unchecked")
  Graph(int V)
  {
    adj = new Vector[V];
    for (int i = 0; i < adj.length; i++)
    {
      adj[i] = new Vector<>();
    }
    this.V = V;
  }
 
  void addEdge(int v, int w)
  {
 
    // Add w to v’s list.
    adj[v].add(w);
 
    // Add v to w's list.
    adj[w].add(v);
  }
 
  int BFS(int s, int l)
  {
 
    // Mark all the vertices
    // as not visited
    boolean[] visited = new boolean[V];
    int[] level = new int[V];
 
    for (int i = 0; i < V; i++)
    {
      visited[i] = false;
      level[i] = 0;
    }
 
    // Create a queue for BFS
    Queue<Integer> queue = new LinkedList<>();
 
    // Mark the current node as
    // visited and enqueue it
    visited[s] = true;
    queue.add(s);
    level[s] = 0;
    int count = 0;
    while (!queue.isEmpty())
    {
 
      // Dequeue a vertex from
      // queue and print it
      s = queue.peek();
      queue.poll();
 
      Vector<Integer> list = adj[s];
      // Get all adjacent vertices
      // of the dequeued vertex s.
      // If a adjacent has not been
      // visited, then mark it
      // visited and enqueue it
      for (int i : list)
      {
        if (!visited[i])
        {
          visited[i] = true;
          level[i] = level[s] + 1;
          queue.add(i);
        }
      }
 
      count = 0;
      for (int i = 0; i < V; i++)
        if (level[i] == l)
          count++;
    }
    return count;
  }
}
class GFG {
 
  // Driver code
  public static void main(String[] args)
  {
 
    // Create a graph given
    // in the above diagram
    Graph g = new Graph(6);
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 3);
    g.addEdge(2, 4);
    g.addEdge(2, 5);
    int level = 2;
    System.out.print(g.BFS(0, level));
  }
}
 
// This code is contributed by Rajput-Ji


Python3




# Python3 program to print
# count of nodes at given level.
from collections import deque
  
adj = [[] for i in range(1001)]
  
def addEdge(v, w):
     
    # Add w to v’s list.
    adj[v].append(w)
  
    # Add v to w's list.
    adj[w].append(v)
  
def BFS(s, l):
     
    V = 100
     
    # Mark all the vertices
    # as not visited
    visited = [False] * V
    level = [0] * V
  
    for i in range(V):
        visited[i] = False
        level[i] = 0
  
    # Create a queue for BFS
    queue = deque()
  
    # Mark the current node as
    # visited and enqueue it
    visited[s] = True
    queue.append(s)
    level[s] = 0
  
    while (len(queue) > 0):
         
        # Dequeue a vertex from
        # queue and print
        s = queue.popleft()
        #queue.pop_front()
  
        # Get all adjacent vertices
        # of the dequeued vertex s.
        # If a adjacent has not been
        # visited, then mark it
        # visited and enqueue it
        for i in adj[s]:
            if (not visited[i]):
  
                # Setting the level
                # of each node with
                # an increment in the
                # level of parent node
                level[i] = level[s] + 1
                visited[i] = True
                queue.append(i)
  
    count = 0
    for i in range(V):
        if (level[i] == l):
            count += 1
             
    return count
  
# Driver code
if __name__ == '__main__':
     
    # Create a graph given
    # in the above diagram
    addEdge(0, 1)
    addEdge(0, 2)
    addEdge(1, 3)
    addEdge(2, 4)
    addEdge(2, 5)
  
    level = 2
  
    print(BFS(0, level))
     
# This code is contributed by mohit kumar 29


C#




// C# program to print count of nodes
// at given level.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
// This class represents
// a directed graph
// using adjacency
// list representation
class Graph{
 
// No. of vertices    
private int _V;
 
LinkedList<int>[] _adj;
 
public Graph(int V)
{
    _adj = new LinkedList<int>[V];
 
    for(int i = 0; i < _adj.Length; i++)
    {
        _adj[i] = new LinkedList<int>();
    }
    _V = V;
}
 
public void AddEdge(int v, int w)
{
     
    // Add w to v’s list.
    _adj[v].AddLast(w);
}
 
public int BreadthFirstSearch(int s,int l)
{
     
    // Mark all the vertices
    // as not visited
    bool[] visited = new bool[_V];
    int[] level = new int[_V];
     
    for(int i = 0; i < _V; i++)
    {
        visited[i] = false;
        level[i] = 0;
    }
     
    // Create a queue for BFS
    LinkedList<int> queue = new LinkedList<int>();
     
    // Mark the current node as
    // visited and enqueue it
    visited[s] = true;
    level[s] = 0;
    queue.AddLast(s);        
 
    while(queue.Any())
    {
         
        // Dequeue a vertex from
        // queue and print it
        s = queue.First();
         
        // Console.Write( s + " " );
        queue.RemoveFirst();
 
        LinkedList<int> list = _adj[s];
 
        foreach(var val in list)            
        {
            if (!visited[val])
            {
                visited[val] = true;
                level[val] = level[s] + 1;
                queue.AddLast(val);
            }
        }
    }
     
    int count = 0;
    for(int i = 0; i < _V; i++)
        if (level[i] == l)
            count++;
             
    return count;
}
}
 
// Driver code
class GFG{
     
static void Main(string[] args)
{
     
    // Create a graph given
    // in the above diagram
    Graph g = new Graph(6);
 
    g.AddEdge(0, 1);
    g.AddEdge(0, 2);
    g.AddEdge(1, 3);
    g.AddEdge(2, 4);
    g.AddEdge(2, 5);
 
    int level = 2;
     
    Console.WriteLine(g.BreadthFirstSearch(0, level));
}
}
 
// This code is contributed by anvudemy1


Javascript




<script>
 
// JavaScript Program to print
// count of nodes
// at given level.
     
    let V;
   
    let adj=new Array(1001);
    for(let i=0;i<adj.length;i++)
    {
        adj[i]=[];
    }
     
    function addEdge(v,w)
    {
    // Add w to v’s list.
    adj[v].push(w);
  
    // Add v to w's list.
    adj[w].push(v);
    }
     
    function BFS(s,l)
    {
        V=100;
     // Mark all the vertices
    // as not visited
    let visited = new Array(V);
    let level = new Array(V);
  
    for (let i = 0; i < V; i++)
    {
      visited[i] = false;
      level[i] = 0;
    }
  
    // Create a queue for BFS
    let queue = [];
  
    // Mark the current node as
    // visited and enqueue it
    visited[s] = true;
    queue.push(s);
    level[s] = 0;
    let count = 0;
    while (queue.length!=0)
    {
  
      // Dequeue a vertex from
      // queue and print it
      s = queue[0];
      queue.shift();
  
      let list = adj[s];
      // Get all adjacent vertices
      // of the dequeued vertex s.
      // If a adjacent has not been
      // visited, then mark it
      // visited and enqueue it
      for (let i=0;i<list.length;i++)
      {
        if (!visited[list[i]])
        {
          visited[list[i]] = true;
          level[list[i]] = level[s] + 1;
          queue.push(list[i]);
        }
      }
  
      count = 0;
      for (let i = 0; i < V; i++)
        if (level[i] == l)
          count++;
    }
    return count;
  }
 
 
 
// Driver code
 
// Create a graph given
    // in the above diagram
addEdge(0, 1)
addEdge(0, 2)
addEdge(1, 3)
addEdge(2, 4)
addEdge(2, 5)
 
let level = 2;
document.write(BFS(0, level));
     
     
 
// This code is contributed by unknown2108
 
</script>


Output

3

Time Complexity: O(V+E)
Auxiliary Space: O(V)



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
Modify a Binary Tree by adding a level of nodes with given value at a specified level
Given a Binary Tree consisting of N nodes and two integers K and L, the task is to add one row of nodes of value K at the Lth level, such that the orientation of the original tree remains unchanged. Examples: Input: K = 1, L = 2 Output:11 12 34 5 6 Explanation:Below is the tree after inserting node with value 1 in the K(= 2) th level. Input: K = 1,
15+ min read
Level of Each node in a Tree from source node (using BFS)
Given a tree with v vertices, find the level of each node in a tree from the source node. Examples: Input : Output : Node Level 0 0 1 1 2 1 3 2 4 2 5 2 6 2 7 3 Explanation : Input: Output : Node Level 0 0 1 1 2 1 3 2 4 2 Explanation: Approach: BFS(Breadth-First Search) is a graph traversal technique where a node and its neighbours are visited first
8 min read
Count the number of nodes at a given level in a tree using DFS
Given an integer l and a tree represented as an undirected graph rooted at vertex 0. The task is to print the number of nodes present at level l. Examples:  Input: l = 2   Output: 4  We have already discussed the BFS approach, in this post we will solve it using DFS. Approach: The idea is to traverse the graph in a DFS manner. Take two variables, c
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: 11Explanation:For the first level, the 1st node is
15 min read
Difference between sums of odd level and even level nodes in an N-ary Tree
Given an N-ary Tree rooted at 1, the task is to find the difference between the sum of nodes at the odd level and the sum of nodes at even level. Examples: Input: 4 / | \ 2 3 -5 / \ / \ -1 3 -2 6Output: 10Explanation:Sum of nodes at even levels = 2 + 3 + (-5) = 0Sum of nodes at odd levels = 4 + (-1) + 3 + (-2) + 6 = 10Hence, the required difference
9 min read
Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
Given a Binary Search Tree, the task is to print the nodes of the BST in the following order: If the BST contains levels numbered from 1 to N then, the printing order is level 1, level N, level 2, level N - 1, and so on.The top-level order (1, 2, …) nodes are printed from left to right, while the bottom level order (N, N-1, ...) nodes are printed f
15+ min read
Calculate sum of all nodes present in a level for each level of a Tree
Given a Generic Tree consisting of N nodes (rooted at 0) where each node is associated with a value, the task for each level of the Tree is to find the sum of all node values present at that level of the tree. Examples: Input: node_number = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, node_values = { 2, 3, 4, 4, 7, 6, 2, 3, 9, 1 } Output: Sum of level 0 = 2S
14 min read
Difference between sums of odd level and even level nodes of a Binary Tree
Given a Binary Tree, find the difference between the sum of nodes at odd level and the sum of nodes at even level. Consider root as level 1, left and right children of root as level 2 and so on. For example, in the following tree, sum of nodes at odd level is (5 + 1 + 4 + 8) which is 18. And sum of nodes at even level is (2 + 6 + 3 + 7 + 9) which i
15+ min read
Level Order Traversal (Breadth First Search or BFS) of Binary Tree
Level Order Traversal technique is defined as a method to traverse a Tree such that all nodes present in the same level are traversed completely before traversing the next level. Example: Input: Output:12 34 5 Recommended PracticeLevel order traversalTry It!How does Level Order Traversal work?The main idea of level order traversal is to traverse al
15+ min read
Article Tags :
Practice Tags :