Find Shortest Path in a Tree
Given a tree with 'N' nodes and 'N - 1' distinct edges, along with two nodes 'N1' and 'N2', find and print the shortest path between 'N1' and 'N2'.
Explanation:
A tree is a nonlinear hierarchical data structure composed of nodes connected by edges. It has no cycles, all node values are unique, and the nodes 'N1' and 'N2' always exist in the tree.
Input:
The first line of input contains an integer 'T' denoting the number of test cases. Each test case consists of two parts:
1. The first part is the tree represented in level order format: ROOT_DATA, 'N' (number of children), followed by 'N' children, repeated for every node.
2. The second part contains two space-separated integers 'N1' and 'N2'.
Output:
For each test case, output a single line showing the shortest path from 'N1' to 'N2'.
Example:
Input:
T = 1
Tree = 20 2 10 35 2 5 15 2 30 42 0 1 13 0 0 0
N1, N2 = 15 35
Output:
15 10 20 35
Constraints:
- 1 <= T <= 10^2
- 1 <= N <= 25 * 10^2
- 1 <= NODE_DATA <= 10^5
- 1 <= N1, N2 <= 10^5
Time Limit: 1 second
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.

AnswerBot
4mo
Find the shortest path between two nodes in a tree.
Use BFS to traverse the tree and find the shortest path between the two nodes.
Maintain a parent array to backtrack from the target node to the source...read more
Help your peers!
Add answer anonymously...
Morgan Stanley Software Developer interview questions & answers
A Software Developer was asked 8mo agoQ. Given an integer array nums and an integer k, return the kth largest element in ...read more
A Software Developer was asked 9mo agoQ. Explain the concept of a HashMap.
A Software Developer was asked Q. Why do you want to work at Morgan Stanley?
Popular interview questions of Software Developer
A Software Developer was asked 5mo agoQ1. What is abstraction?
A Software Developer was asked 8mo agoQ2. Given an integer array nums and an integer k, return the kth largest element in ...read more
A Software Developer was asked 9mo agoQ3. Explain the concept of a HashMap.
>
Morgan Stanley Software Developer Interview Questions
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

