Loading...
You are given the root of a binary tree with distinct node values, the value of a target node that exists in the tree, and a non-negative integer k.
The distance between two nodes is the number of edges on the path connecting them, moving through parent or child links in either direction.
Return the values of every node whose distance from the target node is exactly k. You can return the values in any order.
Your function receives root as a TreeNode. The node type is provided for you, with val, left, and right fields.
The examples below write the tree as its level-order traversal, where null marks a missing child of a listed node and trailing nulls are omitted. That is only how the input is displayed; the decoding is done for you.
Node.val ≤500Node.val are unique.target is the value of one of the nodes in the tree.The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.
The tree has only one node, so no node can be a distance of 3 from it.
Click "Run" to test with sample cases or "Submit" to run all tests.