Print Nodes at Distance K from a Given Node
Given an arbitrary binary tree, a node of the tree, and an integer 'K', find all nodes that are at a distance K from the specified node, and return a list of these nodes.
The distance between two nodes in a binary tree is defined as the number of connections/edges in the path between the two nodes.
Input:
The first line of the input contains an integer T, denoting the number of test cases to run.
For each test case:
- The first line contains the values of the nodes of the tree in level order format (-1 representing a NULL node).
- The second line contains the value of the target node.
- The third line contains the integer K, representing the distance at which nodes are to be found.
Output:
For each test case, output the values of all nodes at distance = K from the specified target node.
Example:
The input example for the tree could be:
3
5 1
6 2 0 8
-1 -1 7 4 -1 -1 -1 -1
-1 -1 -1 -1
target: 5
K: 1
Output:
1 6 2
Constraints:
- 1 <= T <= 100
- 1 <= N <= 3000
- 0 <= K <= 3000
- 0 <= nodeValue <= 3000
- Time Limit: 1 sec
Note:
1. A binary tree is a tree in which each node has at most two children.
2. The given tree will be non-empty.
3. The given tree can have multiple nodes with the same value.
4. If no nodes are at distance K from the given node, return an empty list.
5. You can return the list of values of valid nodes in any order.

AnswerBot
4mo
Given a binary tree, a target node, and an integer K, find all nodes at distance K from the target node.
Traverse the binary tree to find the target node.
From the target node, perform a depth-first sea...read more
Help your peers!
Add answer anonymously...
Paytm Software Developer Intern interview questions & answers
A Software Developer Intern was asked Q. Find All Pairs Adding Up to Target Given an array of integers ARR of length N an...read more
A Software Developer Intern was asked Q. Binary Tree Diameter Problem Statement You are given a Binary Tree, and you need...read more
A Software Developer Intern was asked Q. Next Greater Element Problem Statement Given a list of integers of size N, your ...read more
Popular interview questions of Software Developer Intern
A Software Developer Intern was asked Q1. Find All Pairs Adding Up to Target Given an array of integers ARR of length N an...read more
A Software Developer Intern was asked Q2. Binary Tree Diameter Problem Statement You are given a Binary Tree, and you need...read more
A Software Developer Intern was asked Q3. Next Greater Element Problem Statement Given a list of integers of size N, your ...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

