Nodes at Distance K from Target Node in Binary Tree

Given a Binary Tree of distinct integers and two integers, target and K, return a list of values of all nodes located at a distance K from the target node.

Explanation:

The distance between two nodes u and v is defined as the number of edges in the shortest path from u to v.

Input:

The first line contains an integer 'T', representing the number of test cases. Each test case consists of two parts:
1. A single line of space-separated integers representing the Binary Tree in level order, where -1 represents a null node.
2. Two integers, target and K.

Output:

A list of space-separated integers representing the values of nodes that are at distance K from the target node. Each test case should be printed on a new line.

Example:

Input:
1
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
2 2
Output:
7 5

Constraints:

  • 1 ≤ T ≤ 100
  • 0 ≤ N ≤ 3000
  • 0 ≤ data ≤ 10^4
  • 0 ≤ target ≤ 10^4
  • 1 ≤ K ≤ 3000

Where N is the total number of nodes in the binary tree, and data is the value of the binary tree node.

Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Be the first one to answer
Add answer anonymously...
Media.net Software Services (India) 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