All Nodes Distance K in Binary Tree
MediumP2Coding
Given a binary tree, a target node in it and an integer k, return the values of all nodes that are exactly k edges away from the target. Distance is measured along tree edges and may go up through parents as well as down. Return the values in any order.
The target is given as a value; the harness passes you the node of the tree that holds it. All values in the tree are unique.
Example 1
- Input
- root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
- Output
- [7,4,1]
- Why
- 7 and 4 are below 5; 1 is reached through the parent 3.
Example 2
- Input
- root = [1], target = 1, k = 3
- Output
- []
Constraints
- 1 <= number of nodes <= 500
- 0 <= Node.val <= 500
- Values are unique and target is in the tree.
- 0 <= k <= 1000
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 9. ⌘Enter runs, ⌘⇧Enter submits.