Given the root of a binary tree and a key x in it, find the distance of the given key from the root. Distance means the number of edges between two nodes.
Examples:
Input : x = 45,
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.
Approach: The idea is to traverse the tree from the root. Check if x is present at the root or in the left subtree or in the right subtree. We initialize distance as -1 and add 1 to distance for all three cases.
Implementation:
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 x)
{
if (root == NULL)
return -1;
int dist = -1;
if ((root->data == x) ||
(dist = findDistance(root->left, x)) >= 0 ||
(dist = findDistance(root->right, x)) >= 0)
return dist + 1;
return dist;
}
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 = null ;
temp.right = null ;
return temp;
}
static int findDistance(Node root, int x)
{
if (root == null )
return - 1 ;
int dist = - 1 ;
if ((root.data == x) ||
(dist = findDistance(root.left, x)) >= 0 ||
(dist = findDistance(root.right, x)) >= 0 )
return dist + 1 ;
return dist;
}
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
class newNode:
def __init__( self , item):
self .data = item
self .left = self .right = None
def findDistance(root, x):
if (root = = None ):
return - 1
dist = - 1
if (root.data = = x):
return dist + 1
else :
dist = findDistance(root.left, x)
if dist > = 0 :
return dist + 1
else :
dist = findDistance(root.right, x)
if dist > = 0 :
return dist + 1
return dist
if __name__ = = '__main__' :
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 )
print (findDistance(root, 45 ))
|
C#
using System;
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 = null ;
temp.right = null ;
return temp;
}
static int findDistance(Node root, int x)
{
if (root == null )
return -1;
int dist = -1;
if ((root.data == x) ||
(dist = findDistance(root.left, x)) >= 0 ||
(dist = findDistance(root.right, x)) >= 0)
return dist + 1;
return dist;
}
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(data)
{
this .data = data;
this .left = this .right = null ;
}
}
function findDistance(root, x)
{
if (root == null )
return -1;
let dist = -1;
if ((root.data == x) ||
(dist = findDistance(root.left, x)) >= 0 ||
(dist = findDistance(root.right, x)) >= 0)
return dist + 1;
return dist;
}
let root = new Node(5);
root.left = new Node(10);
root.right = new Node(15);
root.left.left = new Node(20);
root.left.right = new Node(25);
root.left.right.right = new Node(45);
root.right.left = new Node(30);
root.right.right = new Node(35);
document.write(findDistance(root, 45));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Approach 2: Iterative Approach
The above recursive approach can also be converted to an iterative approach by using a queue. Here is the iterative approach:
- Start from the root node of the binary tree.
- Create a queue and add the root node to the queue.
- Create a map to store the parent of each node. Initialize the map with the root node’s parent as NULL.
- Create a variable to keep track of the distance from the root node.
-
While the queue is not empty, dequeue a node and check if it is the target node.
- If the node is the target node, return the distance from the root node.
- If the node is not the target node, enqueue its left and right children (if they exist) and update their parent in the map.
- Increment the distance from the root node.
- Repeat steps 5-8 until the queue is empty or the target node is found.
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 x) {
if (root == NULL) {
return -1;
}
queue<Node*> q;
q.push(root);
int dist = 0;
while (!q.empty()) {
int size = q.size();
for ( int i = 0; i < size; i++) {
Node* curr = q.front();
q.pop();
if (curr->data == x) {
return dist;
}
if (curr->left) {
q.push(curr->left);
}
if (curr->right) {
q.push(curr->right);
}
}
dist++;
}
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.LinkedList;
import java.util.Queue;
public class Main {
static class Node {
int data;
Node left, right;
Node( int item) {
data = item;
left = right = null ;
}
}
static int findDistance(Node root, int x) {
if (root == null ) {
return - 1 ;
}
Queue<Node> queue = new LinkedList<>();
queue.add(root);
int dist = 0 ;
while (!queue.isEmpty()) {
int size = queue.size();
for ( int i = 0 ; i < size; i++) {
Node curr = queue.poll();
if (curr.data == x) {
return dist;
}
if (curr.left != null ) {
queue.add(curr.left);
}
if (curr.right != null ) {
queue.add(curr.right);
}
}
dist++;
}
return - 1 ;
}
public static void main(String[] args) {
Node root = new Node( 5 );
root.left = new Node( 10 );
root.right = new Node( 15 );
root.left.left = new Node( 20 );
root.left.right = new Node( 25 );
root.left.right.right = new Node( 45 );
root.right.left = new Node( 30 );
root.right.right = new Node( 35 );
System.out.println(findDistance(root, 45 ));
}
}
|
Python3
from queue import Queue
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def findDistance(root, x):
if root is None :
return - 1
q = Queue()
q.put(root)
dist = 0
while not q.empty():
size = q.qsize()
for i in range (size):
curr = q.get()
if curr.data = = x:
return dist
if curr.left:
q.put(curr.left)
if curr.right:
q.put(curr.right)
dist + = 1
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;
public class Node
{
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
public class GFG
{
public static int FindDistance(Node root, int x)
{
if (root == null )
{
return -1;
}
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
int dist = 0;
while (q.Count > 0)
{
int size = q.Count;
for ( int i = 0; i < size; i++)
{
Node curr = q.Dequeue();
if (curr.data == x)
{
return dist;
}
if (curr.left != null )
{
q.Enqueue(curr.left);
}
if (curr.right != null )
{
q.Enqueue(curr.right);
}
}
dist++;
}
return -1;
}
public static void Main()
{
Node root = new Node(5);
root.left = new Node(10);
root.right = new Node(15);
root.left.left = new Node(20);
root.left.right = new Node(25);
root.left.right.right = new Node(45);
root.right.left = new Node(30);
root.right.right = new Node(35);
Console.WriteLine(FindDistance(root, 45));
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .left = null ;
this .right = null ;
}
}
function findDistance(root, x) {
if (root === null ) {
return -1;
}
let queue = [];
queue.push(root);
let dist = 0;
while (queue.length > 0) {
let size = queue.length;
for (let i = 0; i < size; i++) {
let curr = queue.shift();
if (curr.data === x) {
return dist;
}
if (curr.left) {
queue.push(curr.left);
}
if (curr.right) {
queue.push(curr.right);
}
}
dist++;
}
return -1;
}
let root = new Node(5);
root.left = new Node(10);
root.right = new Node(15);
root.left.left = new Node(20);
root.left.right = new Node(25);
root.left.right.right = new Node(45);
root.right.left = new Node(30);
root.right.right = new Node(35);
console.log(findDistance(root, 45));
|
Time Complexity: O(n) where n is the number of nodes in the tree.
Space Complexity: O(w) where w is the maximum width of the tree.