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.
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