Closest Leaf in a Binary Tree

Ninja is stuck in a maze represented as a binary tree, and he is at a specific node ‘X’. Help Ninja find the shortest path to the nearest leaf node, which is considered an exit point.

Explanation:

The problem is to determine the minimum distance from a given node 'X' to any leaf node in a binary tree. The leaves are the exit points, and Ninja needs this information to decide which path to take to escape the maze.

Input:
The first line of the input is an integer 'T' indicating the number of test cases.
For each test case, the first line is the integer 'X', Ninja's current node.
The second line provides the binary tree in level order format, where each node value is separated by a space. Use -1 to represent a null node.
Output:
For each test case, return the minimum distance from node 'X' to a nearest leaf node.
Example:
Input: 
62
15 40 62 -1 -1 10 20 -1 -1 -1 -1
Output:
1

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 3000
  • 1 <= DATA <= 10^5, DATA != -1
Note:
Node ‘X’ will be unique and exists in the tree. You don't need to print the output; implement the function to return the answer.
Be the first one to answer
Add answer anonymously...
Josh Technology Group Software Developer Intern 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