(Translated by https://www.hiragana.jp/)
Level of Each node in a Tree from source node (using BFS) - GeeksforGeeks
Open In App

Level of Each node in a Tree from source node (using BFS)

Last Updated : 01 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a tree with v vertices, find the level of each node in a tree from the source node.

Examples: 

Input :   

Level of Each node in a Tree from source node using BFS

Output :  Node      Level
           0          0
           1          1
           2          1
           3          2
           4          2
           5          2
           6          2
           7          3

Explanation : 

Level of Each node in a Tree from source node using BFS

Input:

Level of Each node in a Tree from source node using BFS

Output :  Node      Level
           0          0
           1          1
           2          1
           3          2
           4          2
Explanation:

Level of Each node in a Tree from source node using BFS

Approach: 
BFS(Breadth-First Search) is a graph traversal technique where a node and its neighbours are visited first and then the neighbours of neighbours. In simple terms, it traverses level-wise from the source. First, it traverses level 1 nodes (direct neighbours of source node) and then level 2 nodes (neighbours of source node) and so on. The BFS can be used to determine the level of each node from a given source node.

Algorithm: 

  1. Create the tree, a queue to store the nodes and insert the root or starting node in the queue. Create an extra array level of size v (number of vertices) and create a visited array.
  2. Run a loop while size of queue is greater than 0.
  3. Mark the current node as visited.
  4. Pop one node from the queue and insert its childrens (if present) and update the size of the inserted node as level[child] = level[node] + 1.
  5. Print all the node and its level.

Implementation: 

C++
// CPP Program to determine level of each node
// and print level
#include <bits/stdc++.h>
using namespace std;

// function to determine level of each node starting
// from x using BFS
void printLevels(vector<int> graph[], int V, int x)
{
    // array to store level of each node
    int level[V];
    bool marked[V];

    // create a queue
    queue<int> que;

    // enqueue element x
    que.push(x);

    // initialize level of source node to 0
    level[x] = 0;

    // marked it as visited
    marked[x] = true;

    // do until queue is empty
    while (!que.empty()) {

        // get the first element of queue
        x = que.front();

        // dequeue element
        que.pop();

        // traverse neighbors of node x
        for (int i = 0; i < graph[x].size(); i++) {
            // b is neighbor of node x
            int b = graph[x][i];

            // if b is not marked already
            if (!marked[b]) {

                // enqueue b in queue
                que.push(b);

                // level of b is level of x + 1
                level[b] = level[x] + 1;

                // mark b
                marked[b] = true;
            }
        }
    }

    // display all nodes and their levels
    cout << "Nodes"
         << "    "
         << "Level" << endl;
    for (int i = 0; i < V; i++)
        cout << " " << i << "   -->   " << level[i] << endl;
}

// Driver Code
int main()
{
    // adjacency graph for tree
    int V = 8;
    vector<int> graph[V];

    graph[0].push_back(1);
    graph[0].push_back(2);
    graph[1].push_back(3);
    graph[1].push_back(4);
    graph[1].push_back(5);
    graph[2].push_back(5);
    graph[2].push_back(6);
    graph[6].push_back(7);

    // call levels function with source as 0
    printLevels(graph, V, 0);

    return 0;
}
Java Python3 C# JavaScript

Output
Nodes    Level
 0   -->   0
 1   -->   1
 2   -->   1
 3   -->   2
 4   -->   2
 5   -->   2
 6   -->   2
 7   -->   3

Complexity Analysis: 

  • Time Complexity: O(n). 
    In BFS traversal every node is visited only once, so Time Complexity is O(n).
  • Space Complexity: O(n). 
    The space is required to store the nodes in a queue.

Level of Each node in a Tree from source node (using BFS)
Article Tags :
Practice Tags :

Similar Reads