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.
Be the first one to answer
Add answer anonymously...
Top Tower Research Capital LLC Software Developer interview questions & answers
Popular interview questions of Software Developer
>
Tower Research Capital LLC Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
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
Get AmbitionBox app