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.

AnswerBot
4mo
Find the minimum distance from a given node to the nearest leaf node in a binary tree.
Traverse the binary tree from the given node 'X' to find the nearest leaf node.
Use a queue for level order travers...read more
Help your peers!
Add answer anonymously...
Paytm Software Developer interview questions & answers
A Software Developer was asked 3mo agoQ. Given a sorted array of integers nums and an integer target, write a function to...read more
A Software Developer was asked 7mo agoQ. Given a 2D grid map of '1's (land) and '0's (water), count the number of islands...read more
A Software Developer was asked 8mo agoQ. Given a binary tree, return the vertical order traversal of its nodes' values. (...read more
Popular interview questions of Software Developer
A Software Developer was asked 7mo agoQ1. Given a 2D grid map of '1's (land) and '0's (water), count the number of islands...read more
A Software Developer was asked 8mo agoQ2. Given a binary tree, return the vertical order traversal of its nodes' values. (...read more
A Software Developer was asked 9mo agoQ3. Given a graph and a source node, find the shortest path from the source to all o...read more
Stay ahead in your career. Get AmbitionBox app


Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+
Reviews
10L+
Interviews
4 Cr+
Salaries
1.5 Cr+
Users
Contribute to help millions
AmbitionBox Awards
Get AmbitionBox app

