Distance of each node of a Binary Tree from the root node using BFS
Last Updated :
21 Jun, 2021
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++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node( int x)
{
data = x;
left = right = NULL;
}
};
void findDistance(Node* root, int N)
{
queue<Node*> Q;
Q.push(root);
int level = 0;
int dist[N + 1];
while (!Q.empty()) {
int M = Q.size();
for ( int i = 0; i < M; i++) {
root = Q.front();
Q.pop();
dist[root->data] = level;
if (root->left) {
Q.push(root->left);
}
if (root->right) {
Q.push(root->right);
}
}
level += 1;
}
for ( int i = 1; i <= N; i++) {
cout << dist[i] << " " ;
}
}
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
import java.util.*;
class GFG
{
static class Node
{
int data;
Node left;
Node right;
Node( int x)
{
data = x;
left = right = null ;
}
};
static void findDistance(Node root, int N)
{
Queue<Node> Q = new LinkedList<>();
Q.add(root);
int level = 0 ;
int []dist = new int [N + 1 ];
while (!Q.isEmpty())
{
int M = Q.size();
for ( int i = 0 ; i < M; i++)
{
root = Q.peek();
Q.remove();
dist[root.data] = level;
if (root.left != null )
{
Q.add(root.left);
}
if (root.right != null )
{
Q.add(root.right);
}
}
level += 1 ;
}
for ( int i = 1 ; i <= N; i++)
{
System.out.print(dist[i] + " " );
}
}
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);
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def findDistance(root, N):
Q = []
Q.append(root)
level = 0
dist = [ 0 for i in range (N + 1 )]
while Q:
M = len (Q)
for i in range ( 0 , M):
root = Q[ 0 ]
Q.pop( 0 )
dist[root.data] = level
if root.left:
Q.append(root.left)
if root.right:
Q.append(root.right)
level + = 1
for i in range ( 1 , N + 1 ):
print (dist[i], end = " " )
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)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
class Node
{
public int data;
public Node left;
public Node right;
public Node( int x)
{
data = x;
left = right = null ;
}
};
static void findDistance(Node root, int N)
{
Queue<Node> Q = new Queue<Node>();
Q.Enqueue(root);
int level = 0;
int []dist = new int [N + 1];
while (Q.Count != 0)
{
int M = Q.Count;
for ( int i = 0; i < M; i++)
{
root = Q.Peek();
Q.Dequeue();
dist[root.data] = level;
if (root.left != null )
{
Q.Enqueue(root.left);
}
if (root.right != null )
{
Q.Enqueue(root.right);
}
}
level += 1;
}
for ( int i = 1; i <= N; i++)
{
Console.Write(dist[i] + " " );
}
}
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);
}
}
|
Javascript
<script>
class Node
{
constructor(x) {
this .left = null ;
this .right = null ;
this .data = x;
}
}
function findDistance(root, N)
{
let Q = [];
Q.push(root);
let level = 0;
let dist = new Array(N + 1);
while (Q.length > 0)
{
let M = Q.length;
for (let i = 0; i < M; i++)
{
root = Q[0];
Q.shift();
dist[root.data] = level;
if (root.left != null )
{
Q.push(root.left);
}
if (root.right != null )
{
Q.push(root.right);
}
}
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>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...