Path In A Tree Problem Statement
Given a binary tree with 'N' nodes and a specific node 'X', your goal is to print the path from the root node to the specified node 'X'.
Explanation:
A binary tree is a hierarchical structure where each node has up to two children. The task is to identify a path from the root to a given node within this tree structure.
Input:
The first line contains an integer 'T', representing the number of test cases. Then, the description of test cases follows.
For each test case:
- The first line contains the elements of the tree in level order, separated by spaces. Use -1 for non-existent left or right children.
- The second line contains an integer 'X', indicating the target node value.
Output:
For each test case, print a list of integers that depicts the path from the root to the node 'X'. Each test case's output should be on a new line.
Example:
Input:
T = 1
Elements in level order: 1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
X = 7
Output:
1 3 7
Explanation:
Given the input tree and the target node 'X' equal to 7, we find the path from root (1) to node '7', resulting in path: 1 3 7.
Constraints:
1 <= T <= 10
1 <= N <= 10000
1 <= X <= N
- All node values are unique and range from 1 to N.
- Time limit is 1 second.
Note:
The implementation function does not need to print anything; this has been managed already. Ensure that no two nodes in the tree contain identical data values. You can assume the tree contains the node value 'X' as given in each test case.

AnswerBot
4mo
Given a binary tree and a target node, find the path from the root to the target node.
Traverse the binary tree from the root to the target node using depth-first search (DFS).
Store the path from the r...read more
Help your peers!
Add answer anonymously...
Amazon Software Developer interview questions & answers
A Software Developer was asked 1mo agoQ. What is HTML?
A Software Developer was asked 1mo agoQ. What is MySQL?
A Software Developer was asked 2mo agoQ. Given two strings s and t, return true if they are equal when both are typed int...read more
Popular interview questions of Software Developer
A Software Developer was asked 1mo agoQ1. What is HTML?
A Software Developer was asked 1mo agoQ2. What is MySQL?
A Software Developer was asked 2mo agoQ3. What is the system design for the cart feature in an e-commerce website?
Top HR questions asked in Amazon Software Developer
A Software Developer was asked 1mo agoQ1. Tell me about a time you had to get to the root cause of a problem
A Software Developer was asked 5mo agoQ2. What are the short-term and long-term goals for the team or organization?
A Software Developer was asked 5mo agoQ3. Why do you want to work at Amazon?
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

