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


Binary Tree is a non-linear data structure. It has a maximum of two children and each node contain three things that are data value, left and right pointer. The top node is called the root node and the last node which does contain any children is called the leave node.

In this problem, we have given a binary tree. It has N nodes in the range from 1 to N (both inclusive) and our task is to find the distance of each node of a binary tree from the root node using BFS.

Examples

Let's see examples with explanations below to understand the problem in a better way.

Input

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

Output

2 1 2 1 3 3 0

Explanation

6 is the root node, so its distance is 0

3 and 1 are present at level 1 so their distance is 1

2 and 0 are present at the next level and remaining 4 and 5 at the next.

BFS Approach

In this approach, we are going to implement the traditional bfs approach to traverse a binary tree or a tree level-wise.

  • First, we are going to define the class to give a structure to the binary tree in which we will define an integer data type that will store the value of the current node and there will be two pointers that will store the address to the left and right child.

  • Next, we will create a function that will take the root as the parameter and in which we will define a queue to store all the elements to get them level-wise.

  • After that, we are going to use nested while loops to get the current level nodes and add the next level nodes to it. At the same time, we will add the level numbers to the current node's respective position in the array.

  • Later we will print all the node values and will return to the main function.

Example

#include <bits/stdc++.h>
using namespace std;
class Node{
public:
   int data; // variable to store the data 
   Node* left; // variable to store the left child address 
   Node* right; // variable to store the right child address     
   // constructor to initialize the values 
   Node(int x){
      data = x;
      left = nullptr;
      right = nullptr;
   }
};
// function to get the required distance from the root 
void findDis(Node* root, int totalNodes){
   // if root is nullptr 
   if(root == nullptr){
      return; 
   }
   // defining queue and  insert root into it
   queue<Node*>q;
   q.push(root);
   // variable to count the distance from root 
   int countLevel = 0;
   // defining the array to store the total Nodes distance from the root 
   int arr[totalNodes];
   // using while loop traverse over the queue apply bfs algorithm 
   while(q.size() > 0){
      // variable to define the total number of elements in the current level 
      int cur = q.size();
      // using nested while loop to traverse the current level
      while(cur--){
         // get the front node of the queue remove the front node
         Node* cur = q.front();
         q.pop();
         // store the distance for the current node 
         arr[cur->data] = countLevel;    
         // if the left and right child are not null then add them to queue
         if(cur->left){
            q.push(cur->left);
         }
         if(cur->right){
            q.push(cur->right);
         }
      }
      // increase the level 
      countLevel += 1;
   }
   // print all the values of the current node 
   for(int i = 0; i < totalNodes; i++){
      cout<<arr[i] << " ";
   }
   cout<<endl;
}
int main(){
   // given inputs 
   int totalNodes = 7;
   Node* root = new Node(6);
   root->left = new Node(3);
   root->right = new Node(1);
   root->left->left = new Node(2);
   root->left->right = new Node(0);
   root->left->right->left = new Node(5);
   root->left->right->right = new Node(4);
   // calling the function 
   cout<<"The distance of all the nodes from the root node is: "<<endl;
   findDis(root, totalNodes);
   return 0;
}

Output

The distance of all the nodes from the root node is: 
2 1 2 1 3 3 0

Time and Space Complexity

The time complexity of the above code is O(N), as we traverse each node of the tree using the BFS method, where N is the total number of nodes.

The space complexity of the above code is O(N), as we are storing each node distance from the root node as a total number of nodes is N and we are using extra space in the form of a queue.

Conclusion

In this tutorial, we have implemented a C++ program to find the Distance of each node of a Binary Tree from the root node using BFS. We have implemented the program as the traditional BFS works using the queue we have traversed each level and added all the values of the next level to queue again to get all. The time complexity of the program is O(N) which is linear as we just visit each node only once, the same goes for the space complexity.

Updated on: 24-Aug-2023

63 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements