New update is available. Click here to update.
Close
Topic list
Distance between two nodes of a Tree
MEDIUM
25 mins
Trees
Topics (Covered in this problem)
Problem solved
Skill meter
Trees
-
-
Other topics
Problem solved
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
Arrays
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

# Distance between two nodes of a Tree

Contributed by
Mutiur Rehman khan
Medium
0/80
Avg time to solve 25 mins
Success Rate 60 %
Share

## Problem Statement

#### Distance between two nodes is defined as the minimum number of edges in the path from one node to another.

Detailed explanation ( Input/output format, Notes, Constraints, Images )
##### Sample Input 1:
``````2
5 6 2 4 3 -1 -1 9 7 -1 -1 -1 -1 -1 -1
7 2
1 3 -1 2 -1 -1 -1
2 4
``````
##### Sample Output 1:
``````4
-1
``````
##### Explanation of Sample Input 1:

``````For the first test case, the distance between node 7 and node 2 will be 4 as there are 4 edges between these two given nodes, i.e. 7 -> 4, 4 -> 6, 6 -> 5, and 5 -> 2.

For the second test case, the answer will be -1 as node 4 is not present in the binary tree.
``````
##### Sample Input 2:
``````2
1 2 3 4 5 6 7 8 9 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
7 1
1 2 3 4 5 -1 -1 -1 -1 -1 -1
3 5
``````
##### Sample Output 2:
``````2
3
``````
Auto
Console