Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Distance between two nodes of a Tree
MEDIUM
25 mins
16 upvotes
Trees
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Trees
-
-
Other topics
Problem solved
Badge
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
Linked List
-
-
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
userLevel
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
yellow-spark
0/80
Avg time to solve 25 mins
Success Rate 60 %
Share
16 upvotes

Problem Statement

Given a binary tree and the value of two nodes, find the distance between the given two nodes of the Binary Tree.

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:

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
Reset Code
Full screen
Auto
copy-code
Console