Distance Between Two Nodes in a Binary Tree

Given a binary tree and the values of two distinct nodes, determine the distance between these two nodes in the tree. The distance is defined as the minimum number of edges in the path connecting the two nodes.

Input:

The first line of the input contains an integer ‘T’, which indicates the number of test cases. Each test case consists of the following lines:
- The first line provides the tree's node values in level order, separated by spaces, using ‘-1’ in place of any null nodes. All tree node values are unique.
- The second line contains two integers, Node 1 and Node 2, which represent the values of the nodes whose distance you need to calculate.

Output:

For each test case, output a single integer representing the distance between the two nodes. If either of the nodes is absent from the tree, return -1.

Example:

Input:
1
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
7 5
Output:
3
Explanation:

The tree structure is as follows:
Level 1: 1
Level 2: 2, 3
Level 3: 4 (left of 2), -1, 5 (left of 3), 6 (right of 3)
Level 4: -1, 7, -1, -1, -1, -1 (7 is right of 4)
Here, the distance between node 7 and node 5 is 3 edges: 7 -> 4, 4 -> 2, 2 -> 1, 1 -> 3, 3 -> 5.

Constraints:

  • 1 <= T <= 102
  • 1 <= N <= 3 * 103
  • 0 <= DATA <= 106 and DATA != -1
Note:

You do not need to print anything. Please ensure to implement the specified function to solve the problem.

Be the first one to answer
Add answer anonymously...
Amazon Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter