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 count of pair of nodes at even distance | Set 2 (Using BFS)
Next article icon

Distance of each node of a Binary Tree from the root node using BFS

Last Updated : 21 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 node 2 is 1. 
The distance from the root to node 3 is 1. 
The distance from the root to node 4 is 2. 
The distance from the root to node 5 is 2. 
The distance from the root to node 6 is 2.
 

Input: 

                  5                  / \                4    6              /  \                  3    7           / \              1    2


Output: 3 3 2 1 0 1 2

 
 

Approach: The problem can be solved using BFS technique. The idea is to use the fact that the distance from the root to a node is equal to the level of that node in the binary tree. Follow the steps below to solve the problem:

  • Initialize a queue, say Q, to store the nodes at each level of the tree.
  • Initialize an array, say dist[], where dist[i] stores the distance from the root node to ith of the tree.
  • Traverse the tree using BFS. For every ith node encountered, update dist[i] to the level of that node in the binary tree.
  • Finally, print the dist[] array.

Below is the implementation of the above approach:

C++
// C++ program to implement // the above approach  #include <bits/stdc++.h> using namespace std; struct Node {      // Stores data value     // of the node     int data;      // Stores left subtree     // of a node     Node* left;      // Stores right subtree     // of a node     Node* right;      Node(int x)     {          data = x;         left = right = NULL;     } };  void findDistance(Node* root, int N) {      // Store nodes at each level     // of the binary tree     queue<Node*> Q;      // Insert root into Q     Q.push(root);      // Stores level of a node     int level = 0;      // dist[i]: Stores the distance     // from root node to node i     int dist[N + 1];      // Traverse tree using BFS     while (!Q.empty()) {          // Stores count of nodes         // at current level         int M = Q.size();          // Traverse the nodes at         // current level         for (int i = 0; i < M; i++) {              // Stores front element             // of the queue             root = Q.front();              // Pop front element             // of the queue             Q.pop();              // Stores the distance from             // root node to current node             dist[root->data] = level;              if (root->left) {                  // Push left subtree                 Q.push(root->left);             }              if (root->right) {                  // Push right subtree                 Q.push(root->right);             }         }          // Update level         level += 1;     }      for (int i = 1; i <= N; i++) {          cout << dist[i] << " ";     } }  // Driver Code int main() {      int N = 7;     Node* root = new Node(5);     root->left = new Node(4);     root->right = new Node(6);     root->left->left = new Node(3);     root->left->right = new Node(7);     root->left->left->left = new Node(1);     root->left->left->right = new Node(2);     findDistance(root, N); } 
Java
// Java program to implement // the above approach import java.util.*;  class GFG { static class Node  {      // Stores data value     // of the node     int data;      // Stores left subtree     // of a node     Node left;      // Stores right subtree     // of a node     Node right;     Node(int x)     {         data = x;         left = right = null;     } };  static void findDistance(Node root, int N) {      // Store nodes at each level     // of the binary tree     Queue<Node> Q = new LinkedList<>();      // Insert root into Q     Q.add(root);      // Stores level of a node     int level = 0;      // dist[i]: Stores the distance     // from root node to node i     int []dist = new int[N + 1];      // Traverse tree using BFS     while (!Q.isEmpty())     {          // Stores count of nodes         // at current level         int M = Q.size();          // Traverse the nodes at         // current level         for (int i = 0; i < M; i++)          {              // Stores front element             // of the queue             root = Q.peek();              // Pop front element             // of the queue             Q.remove();              // Stores the distance from             // root node to current node             dist[root.data] = level;              if (root.left != null)              {                  // Push left subtree                 Q.add(root.left);             }              if (root.right != null)             {                  // Push right subtree                 Q.add(root.right);             }         }          // Update level         level += 1;     }      for (int i = 1; i <= N; i++)      {         System.out.print(dist[i] + " ");     } }  // Driver Code public static void main(String[] args) {      int N = 7;     Node root = new Node(5);     root.left = new Node(4);     root.right = new Node(6);     root.left.left = new Node(3);     root.left.right = new Node(7);     root.left.left.left = new Node(1);     root.left.left.right = new Node(2);     findDistance(root, N); } }  // This code is contributed by shikhasingrajput  
Python3
# Python3 program to implement # the above approach class Node:          def __init__(self, data):                  # Stores data value         # of the node         self.data = data                  # Stores left subtree         # of a node         self.left = None                  # Stores right subtree         # of a node         self.right = None  def findDistance(root, N):          # Store nodes at each level     # of the binary tree     Q = []          # Insert root into Q     Q.append(root)          # Stores level of a node     level = 0          # dist[i]: Stores the distance     # from root node to node i     dist = [0 for i in range(N + 1)]          # Traverse tree using BFS     while Q:                  # Stores count of nodes         # at current level         M = len(Q)                  # Traverse the nodes at         # current level         for i in range(0, M):                          # Stores front element             # of the queue             root = Q[0]                          # Pop front element             # of the queue             Q.pop(0)                          #  Stores the distance from             # root node to current node             dist[root.data] = level                          if root.left:                                  # Push left subtree                 Q.append(root.left)             if root.right:                                  # Push right subtree                 Q.append(root.right)                          # Update level         level += 1              for i in range(1, N + 1):         print(dist[i], end = " ")  # Driver code if __name__ == '__main__':          N = 7     root = Node(5)     root.left = Node(4)     root.right = Node(6)     root.left.left = Node(3)     root.left.right = Node(7)     root.left.left.left = Node(1)     root.left.left.right = Node(2)          findDistance(root, N)  # This code is contributed by MuskanKalra1 
C#
// C# program to implement // the above approach using System; using System.Collections.Generic; class GFG {   class Node    {      // Stores data value     // of the node     public int data;      // Stores left subtree     // of a node     public Node left;      // Stores right subtree     // of a node     public Node right;     public Node(int x)     {       data = x;       left = right = null;     }   };    static void findDistance(Node root, int N)   {      // Store nodes at each level     // of the binary tree     Queue<Node> Q = new Queue<Node>();      // Insert root into Q     Q.Enqueue(root);      // Stores level of a node     int level = 0;      // dist[i]: Stores the distance     // from root node to node i     int []dist = new int[N + 1];      // Traverse tree using BFS     while (Q.Count != 0)     {        // Stores count of nodes       // at current level       int M = Q.Count;        // Traverse the nodes at       // current level       for (int i = 0; i < M; i++)        {          // Stores front element         // of the queue         root = Q.Peek();          // Pop front element         // of the queue         Q.Dequeue();          // Stores the distance from         // root node to current node         dist[root.data] = level;          if (root.left != null)          {            // Push left subtree           Q.Enqueue(root.left);         }          if (root.right != null)         {            // Push right subtree           Q.Enqueue(root.right);         }       }        // Update level       level += 1;     }      for (int i = 1; i <= N; i++)      {       Console.Write(dist[i] + " ");     }   }    // Driver Code   public static void Main(String[] args)   {      int N = 7;     Node root = new Node(5);     root.left = new Node(4);     root.right = new Node(6);     root.left.left = new Node(3);     root.left.right = new Node(7);     root.left.left.left = new Node(1);     root.left.left.right = new Node(2);     findDistance(root, N);   } }  // This code is contributed by shikhasingrajput  
JavaScript
<script>      // JavaScript program to implement the above approach          // Structure of a tree node     class Node     {         constructor(x) {            this.left = null;            this.right = null;            this.data = x;         }     }          function findDistance(root, N)     {          // Store nodes at each level         // of the binary tree         let Q = [];          // Insert root into Q         Q.push(root);          // Stores level of a node         let level = 0;          // dist[i]: Stores the distance         // from root node to node i         let dist = new Array(N + 1);          // Traverse tree using BFS         while (Q.length > 0)         {              // Stores count of nodes             // at current level             let M = Q.length;              // Traverse the nodes at             // current level             for (let i = 0; i < M; i++)             {                  // Stores front element                 // of the queue                 root = Q[0];                  // Pop front element                 // of the queue                 Q.shift();                  // Stores the distance from                 // root node to current node                 dist[root.data] = level;                  if (root.left != null)                 {                      // Push left subtree                     Q.push(root.left);                 }                  if (root.right != null)                 {                      // Push right subtree                     Q.push(root.right);                 }             }              // Update level             level += 1;         }          for (let i = 1; i <= N; i++)         {             document.write(dist[i] + " ");         }     }          let N = 7;     let root = new Node(5);     root.left = new Node(4);     root.right = new Node(6);     root.left.left = new Node(3);     root.left.right = new Node(7);     root.left.left.left = new Node(1);     root.left.left.right = new Node(2);     findDistance(root, N);  </script> 

Output: 
3 3 2 1 0 1 2

 

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


Next Article
Find count of pair of nodes at even distance | Set 2 (Using BFS)

K

krish_45
Improve
Article Tags :
  • Misc
  • Tree
  • Queue
  • Searching
  • DSA
  • BFS
  • Tree Traversals
Practice Tags :
  • BFS
  • Misc
  • Queue
  • Searching
  • Tree

Similar Reads

  • Farthest distance of a Node from each Node of a Tree
    Given a Tree, the task is to find the farthest node from each node to another node in the given tree. Examples Input: Output: 2 3 3 3 4 4 4 Explanation: Maximum Distance from Node 1 : 2 (Nodes {5, 6, 7} are at a distance 2) Maximum Distance from Node 2 : 3 (Nodes {6, 7} are at a distance 3) Maximum
    11 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
    8 min read
  • Find distance from root to given node in a binary tree
    Given the root of a binary tree and a key x in it, find the distance of the given key from the root. Dis­tance means the num­ber of edges between two nodes. Examples: Input: x = 45 Output: 3 Explanation: There are three edges on path from root to 45.For more understanding of question, in above tree
    11 min read
  • Distance between two nodes of binary tree with node values from 1 to N
    Given a binary tree with 1 as its root and for any parent i its left child will be 2*i and right child will be 2*i+1. The task is to find the minimum distance between two nodes n1 and n2. 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / \ / \ / \ . . . . . . . . Examples: Input : n1 = 7, n2 = 10 Output : 5 Input : n
    7 min read
  • Find count of pair of nodes at even distance | Set 2 (Using BFS)
    Given a connected acyclic graph with N nodes numbered from 1 to N and N-1 edges, find out the pair of nodes that are at even distance from each other. Note: The graph is represented in the form of an adjacency list. Examples: Input: N = 3, graph = {{}, {2}, {1, 3}, {2}}Output:1Explanation: Here ther
    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
  • Queries to find distance between two nodes of a Binary tree
    Given a binary tree, the task is to find the distance between two keys in a binary tree, no parent pointers are given. The distance between two nodes is the minimum number of edges to be traversed to reach one node from other. We have already discussed a method which uses segment tree to reduce the
    15+ min read
  • Find distance between two nodes of a Binary Tree
    Given a Binary tree, the task is to find the distance between two keys in a binary tree, no parent pointers are given. The distance between two nodes is the minimum number of edges to be traversed to reach one node from another. The given two nodes are guaranteed to be in the binary tree and all nod
    15+ min read
  • Queries to find distance between two nodes of a Binary tree - O(logn) method
    Given a binary tree, the task is to find the distance between two keys in a binary tree, no parent pointers are given. Distance between two nodes is the minimum number of edges to be traversed to reach one node from other. This problem has been already discussed in previous post but it uses three tr
    15+ min read
  • Print path from a node to root of given Complete Binary Tree
    Given an integer N, the task is to find the path from the Nth node to the root of a Binary Tree of the following form: The Binary Tree is a Complete Binary Tree up to the level of the Nth node.The nodes are numbered 1 to N, starting from the root as 1.The structure of the Tree is as follows: 1 / \ 2
    4 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