Iterative program to find distance of a node from root
Given the root of a binary tree and a key x in it, find the distance of the given key from the root node. DisÂtance means numÂber of edges between two nodes.
Examples:
Input : x = 45,
5 is Root of below tree
5
/ \
10 15
/ \ / \
20 25 30 35
\
45
Output : Distance = 3
There are three edges on path
from root to 45.
For more understanding of question,
in above tree distance of 35 is two
and distance of 10 is 1.
Related Problem: Recursive program to find distance of node from root.
Iterative Approach :
- Use level order traversal to traverse the tree iteratively using a queue.
- Keep a variable levelCount to maintain the track of current level.
- To do this, every time on moving to the next level, while pushing a NULL node to the queue also increment the value of the variable levelCount so that it stores the current level number.
- While traversing the tree, check if any node at the current level matches with the given key.
- If yes, then return levelCount.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
Node* newNode( int item)
{
Node* temp = new Node;
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
int findDistance(Node* root, int key)
{
if (root == NULL) {
return -1;
}
if (root->data == key)
return 0;
queue<Node*> q;
q.push(root);
q.push(NULL);
int levelCount = 0;
while (!q.empty()) {
Node* temp = q.front();
q.pop();
if (temp == NULL && !q.empty()) {
q.push(NULL);
levelCount++;
}
else if (temp != NULL) {
if (temp->data == key)
return levelCount;
if (temp->left)
q.push(temp->left);
if (temp->right)
q.push(temp->right);
}
}
return -1;
}
int main()
{
Node* root = newNode(5);
root->left = newNode(10);
root->right = newNode(15);
root->left->left = newNode(20);
root->left->right = newNode(25);
root->left->right->right = newNode(45);
root->right->left = newNode(30);
root->right->right = newNode(35);
cout << findDistance(root, 45);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static class Node
{
int data;
Node left, right;
};
static Node newNode( int item)
{
Node temp = new Node();
temp.data = item;
temp.left = temp.right = null ;
return temp;
}
static int findDistance(Node root, int key)
{
if (root == null )
{
return - 1 ;
}
if (root.data == key)
return 0 ;
Queue<Node> q = new LinkedList<Node>();
q.add(root);
q.add( null );
int levelCount = 0 ;
while (!q.isEmpty())
{
Node temp = q.peek();
q.remove();
if (temp == null && !q.isEmpty())
{
q.add( null );
levelCount++;
}
else if (temp != null )
{
if (temp.data == key)
return levelCount;
if (temp.left != null )
q.add(temp.left);
if (temp.right != null )
q.add(temp.right);
}
}
return - 1 ;
}
public static void main(String[] args)
{
Node root = newNode( 5 );
root.left = newNode( 10 );
root.right = newNode( 15 );
root.left.left = newNode( 20 );
root.left.right = newNode( 25 );
root.left.right.right = newNode( 45 );
root.right.left = newNode( 30 );
root.right.right = newNode( 35 );
System.out.println(findDistance(root, 45 ));
}
}
|
Python3
from collections import deque
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def findDistance(root: Node, key: int ) - > int :
if root is None :
return - 1
if root.data = = key:
return 0
q = deque()
q.append(root)
q.append( None )
levelCount = 0
while q:
temp = q[ 0 ]
q.popleft()
if temp is None and q:
q.append( None )
levelCount + = 1
elif temp:
if temp.data = = key:
return levelCount
if temp.left:
q.append(temp.left)
if temp.right:
q.append(temp.right)
return - 1
if __name__ = = "__main__" :
root = Node( 5 )
root.left = Node( 10 )
root.right = Node( 15 )
root.left.left = Node( 20 )
root.left.right = Node( 25 )
root.left.right.right = Node( 45 )
root.right.left = Node( 30 )
root.right.right = Node( 35 )
print (findDistance(root, 45 ))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
class Node
{
public int data;
public Node left, right;
};
static Node newNode( int item)
{
Node temp = new Node();
temp.data = item;
temp.left = temp.right = null ;
return temp;
}
static int findDistance(Node root, int key)
{
if (root == null )
{
return -1;
}
if (root.data == key)
return 0;
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
q.Enqueue( null );
int levelCount = 0;
while (q.Count!=0)
{
Node temp = q.Peek();
q.Dequeue();
if (temp == null && q.Count!=0)
{
q.Enqueue( null );
levelCount++;
}
else if (temp != null )
{
if (temp.data == key)
return levelCount;
if (temp.left != null )
q.Enqueue(temp.left);
if (temp.right != null )
q.Enqueue(temp.right);
}
}
return -1;
}
public static void Main(String[] args)
{
Node root = newNode(5);
root.left = newNode(10);
root.right = newNode(15);
root.left.left = newNode(20);
root.left.right = newNode(25);
root.left.right.right = newNode(45);
root.right.left = newNode(30);
root.right.right = newNode(35);
Console.WriteLine(findDistance(root, 45));
}
}
|
Javascript
<script>
class Node
{
constructor(item)
{
this .left = null ;
this .right = null ;
this .data = item;
}
}
function newNode(item)
{
let temp = new Node(item);
return temp;
}
function findDistance(root, key)
{
if (root == null )
{
return -1;
}
if (root.data == key)
return 0;
let q = [];
q.push(root);
q.push( null );
let levelCount = 0;
while (q.length > 0)
{
let temp = q[0];
q.shift();
if (temp == null && q.length > 0)
{
q.push( null );
levelCount++;
}
else if (temp != null )
{
if (temp.data == key)
return levelCount;
if (temp.left != null )
q.push(temp.left);
if (temp.right != null )
q.push(temp.right);
}
}
return -1;
}
let root = newNode(5);
root.left = newNode(10);
root.right = newNode(15);
root.left.left = newNode(20);
root.left.right = newNode(25);
root.left.right.right = newNode(45);
root.right.left = newNode(30);
root.right.right = newNode(35);
document.write(findDistance(root, 45));
</script>
|
Time Complexity: O(n) where n = Number of nodes
Space Complexity: O(n)
Last Updated :
08 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...