Print all Nodes at a Distance of K

Hard Problems DSA practice problem on Onlearn.

Difficulty: medium.

Topics: Print all the Nodes at a distance of K in a Binary Tree, Binary Tree, Traversal, Depth-First Search, Breadth-First Search, Recursion, Queue, Graph, dfs, graph traversal, binary tree, recursion, bfs, tree traversal, Nodes at Distance K.

Print All Nodes at Distance K in a Binary Tree Problem Statement Given the root of a binary tree, a target node, and an integer k, return an array of the values of all nodes that have a distance k from the target node. The distance between two nodes is the number of edges in the shortest path between them. Input root: The root node of the binary tree. target: A node in the binary tree. k: An integer representing the required distance. Output An array of integers, where each integer is the value of a node at distance k from the target node. The order of nodes in the output array does not matter. Constraints The number of nodes in the tree is in the range [1, 500]. 0 <= Node.val <= 500 All Node.val are unique. target is a node in the tree. 0 <= k <= 10 Example Example 1: Input: (This array representation means: root is 3, its left child is 5, right child is 1. 5's left is 6, right is 2. 1's left is 0, right is 8. 2's left is 7, right is 4.) Output: Explanation: The nodes at distance 2 from node with value 5 are nodes with values 7, 4, and 1.