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 Graph
  • Practice Graph
  • MCQs on Graph
  • Graph Tutorial
  • Graph Representation
  • Graph Properties
  • Types of Graphs
  • Graph Applications
  • BFS on Graph
  • DFS on Graph
  • Graph VS Tree
  • Transpose Graph
  • Dijkstra's Algorithm
  • Minimum Spanning Tree
  • Prim’s Algorithm
  • Topological Sorting
  • Floyd Warshall Algorithm
  • Strongly Connected Components
  • Advantages & Disadvantages
Open In App
Next Article:
Distance of each node of a Binary Tree from the root node using BFS
Next article icon

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




// Java Program to determine level of each node
// and print level
import java.util.*;
 
class GFG {
 
    // function to determine level of each node starting
    // from x using BFS
    static void printLevels(Vector<Vector<Integer> > graph,
                            int V, int x)
    {
        // array to store level of each node
        int level[] = new int[V];
        boolean marked[] = new boolean[V];
 
        // create a queue
        Queue<Integer> que = new LinkedList<Integer>();
 
        // enqueue element x
        que.add(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.size() > 0) {
 
            // get the first element of queue
            x = que.peek();
 
            // dequeue element
            que.remove();
 
            // traverse neighbors of node x
            for (int i = 0; i < graph.get(x).size(); i++) {
                // b is neighbor of node x
                int b = graph.get(x).get(i);
 
                // if b is not marked already
                if (!marked[b]) {
 
                    // enqueue b in queue
                    que.add(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
        System.out.println("Nodes"
                           + " "
                           + "Level");
        for (int i = 0; i < V; i++)
            System.out.println(" " + i + " --> "
                               + level[i]);
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // adjacency graph for tree
        int V = 8;
        Vector<Vector<Integer> > graph
            = new Vector<Vector<Integer> >();
 
        for (int i = 0; i < V + 1; i++)
            graph.add(new Vector<Integer>());
 
        graph.get(0).add(1);
        graph.get(0).add(2);
        graph.get(1).add(3);
        graph.get(1).add(4);
        graph.get(1).add(5);
        graph.get(2).add(5);
        graph.get(2).add(6);
        graph.get(6).add(7);
 
        // call levels function with source as 0
        printLevels(graph, V, 0);
    }
}
 
// This code is contributed by Arnab Kundu
 
 

Python3




# Python3 Program to determine level
# of each node and print level
import queue
 
# function to determine level of
# each node starting from x using BFS
 
 
def printLevels(graph, V, x):
 
    # array to store level of each node
    level = [None] * V
    marked = [False] * V
 
    # create a queue
    que = queue.Queue()
 
    # enqueue element x
    que.put(x)
 
    # initialize level of source
    # node to 0
    level[x] = 0
 
    # marked it as visited
    marked[x] = True
 
    # do until queue is empty
    while (not que.empty()):
 
        # get the first element of queue
        x = que.get()
 
        # traverse neighbors of node x
        for i in range(len(graph[x])):
 
            # b is neighbor of node x
            b = graph[x][i]
 
            # if b is not marked already
            if (not marked[b]):
 
                # enqueue b in queue
                que.put(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
    print("Nodes", " ", "Level")
    for i in range(V):
        print(" ", i,  " --> ", level[i])
 
 
# Driver Code
if __name__ == '__main__':
 
    # adjacency graph for tree
    V = 8
    graph = [[] for i in range(V)]
 
    graph[0].append(1)
    graph[0].append(2)
    graph[1].append(3)
    graph[1].append(4)
    graph[1].append(5)
    graph[2].append(5)
    graph[2].append(6)
    graph[6].append(7)
 
    # call levels function with source as 0
    printLevels(graph, V, 0)
 
# This code is contributed by PranchalK
 
 

C#




// C# Program to determine level of each node
// and print level
using System;
using System.Collections.Generic;
 
class GFG {
 
    // function to determine level of each node starting
    // from x using BFS
    static void printLevels(List<List<int> > graph, int V,
                            int x)
    {
        // array to store level of each node
        int[] level = new int[V];
        Boolean[] marked = new Boolean[V];
 
        // create a queue
        Queue<int> que = new Queue<int>();
 
        // enqueue element x
        que.Enqueue(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.Count > 0) {
 
            // get the first element of queue
            x = que.Peek();
 
            // dequeue element
            que.Dequeue();
 
            // traverse neighbors of node x
            for (int i = 0; i < graph[x].Count; 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.Enqueue(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
        Console.WriteLine("Nodes"
                          + " "
                          + "Level");
        for (int i = 0; i < V; i++)
            Console.WriteLine(" " + i + " --> " + level[i]);
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        // adjacency graph for tree
        int V = 8;
        List<List<int> > graph = new List<List<int> >();
 
        for (int i = 0; i < V + 1; i++)
            graph.Add(new List<int>());
 
        graph[0].Add(1);
        graph[0].Add(2);
        graph[1].Add(3);
        graph[1].Add(4);
        graph[1].Add(5);
        graph[2].Add(5);
        graph[2].Add(6);
        graph[6].Add(7);
 
        // call levels function with source as 0
        printLevels(graph, V, 0);
    }
}
 
// This code is contributed by Princi Singh
 
 

Javascript




<script>
    
// Javascript Program to determine level of each node
// and print level
 
// function to determine level of each node starting
// from x using BFS
function printLevels(graph, V, x)
{
    // array to store level of each node
    var level = Array(V);
    var marked = Array(V).fill(false);
 
    // create a queue
    var 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.length > 0)
    {
 
        // get the first element of queue
        x = que[0];
 
        // dequeue element
        que.shift();
 
        // traverse neighbors of node x
        for (var i = 0; i < graph[x].length; i++)
        {
            // b is neighbor of node x
            var 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
    document.write("Nodes" + " " + "Level<br>");
    for (var i = 0; i < V; i++)
        document.write(" " + i +" --> " + level[i]+"<br>");
}
 
// Driver Code
// adjacency graph for tree
var V = 8;
var graph = Array.from(Array(V+1), ()=>Array());
 
graph[0].push(1);
graph[0].push(2);
graph[1].push(3);
graph[1].push(4);
graph[1].push(5);
graph[2].push(5);
graph[2].push(6);
graph[6].push(7);
// call levels function with source as 0
printLevels(graph, V, 0);
 
// This code is contributed by importantly.
 
</script>
 
 
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.


Next Article
Distance of each node of a Binary Tree from the root node using BFS
author
shubham_rana_77
Improve
Article Tags :
  • DSA
  • Graph
  • BFS
Practice Tags :
  • BFS
  • Graph

Similar Reads

  • Count the number of nodes at given level in a tree using BFS.
    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 traver
    9 min read
  • Distance of each node of a Binary Tree from the root node using BFS
    Given a Binary tree consisting of N nodes with values in the range [1, N], the task is to find the distance from the root node to every node of the tree. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 Output: 0 1 1 2 2 2 Explanation: The distance from the root to node 1 is 0. The distance from the root to n
    9 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 travers
    8 min read
  • Subtree of all nodes in a tree using DFS
    Given n nodes of a tree and their connections, print Subtree nodes of every node.Subtree of a node is defined as a tree which is a child of a node. The name emphasizes that everything which is a descendant of a tree node is a tree too, and is a subset of the larger tree. Examples : Input: N = 5 0 1
    8 min read
  • Print Binary Tree levels in sorted order | Set 2 (Using set)
    Given a tree, print the level order traversal in sorted order. Examples : Input : 7 / \ 6 5 / \ / \ 4 3 2 1 Output : 7 5 6 1 2 3 4 Input : 7 / \ 16 1 / \ 4 13 Output : 7 1 16 4 13 We have discussed a priority queue based solution in below post.Print Binary Tree levels in sorted order | Set 1 (Using
    5 min read
  • Level Order Successor of a node in Binary Tree
    Given a binary tree and a node in the binary tree, find Levelorder successor of the given node. That is, the node that appears after the given node in the level order traversal of the tree. Note: The task is not just to print the data of the node, you have to return the complete node from the tree.
    9 min read
  • Level of a Node in Binary Tree
    Given a Binary Tree and a key, the task is to find the level of key in the Binary Tree. Examples: Input : key = 4 Output: 3Explanation: The level of the key in above binary tree is 3.Input : key = 10 Output: -1Explanation: Key is not present in the above Binary tree. Table of Content [Expected Appro
    12 min read
  • Print extreme nodes of each level of Binary Tree in alternate order
    Given a binary tree, print nodes of extreme corners of each level but in alternate order.Example: For above tree, the output can be 1 2 7 8 31 - print rightmost node of 1st level - print leftmost node of 2nd level - print rightmost node of 3rd level - print leftmost node of 4th level - print rightmo
    10 min read
  • Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
    Given Preorder traversal of a Binary Search Tree. Then the task is to print leaf nodes of the Binary Search Tree from the given preorder. Examples : Input : preorder[] = {890, 325, 290, 530, 965};Output : 290 530 965Explanation: Below is the representation of BST using preorder array. Approach: To i
    8 min read
  • Print the middle nodes of each level of a Binary Tree
    Given a Binary Tree, the task is to print the middle nodes of each level of a binary tree. Considering M to be the number of nodes at any level, print (M/2)th node if M is odd. Otherwise, print (M/2)th node and ((M/2) + 1)th node. Examples: Input: Below is the given Tree: Output:12 35 1011 67 9Expla
    11 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