Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node.
You can return the answer in any order.
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
Output: [7,4,1]
Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.
Example 2:
Input: root = [1], target = 1, k = 3
Output: []
Constraints:
The number of nodes in the tree is in the range [1, 500].
0 <= Node.val <= 500
All the values Node.val are unique.
target is the value of one of the nodes in the tree.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution{privateMap<TreeNode,TreeNode>p;privateSet<Integer>vis;privateList<Integer>ans;publicList<Integer>distanceK(TreeNoderoot,TreeNodetarget,intk){p=newHashMap<>();vis=newHashSet<>();ans=newArrayList<>();parents(root,null);dfs(target,k);returnans;}privatevoidparents(TreeNoderoot,TreeNodeprev){if(root==null){return;}p.put(root,prev);parents(root.left,root);parents(root.right,root);}privatevoiddfs(TreeNoderoot,intk){if(root==null||vis.contains(root.val)){return;}vis.add(root.val);if(k==0){ans.add(root.val);return;}dfs(root.left,k-1);dfs(root.right,k-1);dfs(p.get(root),k-1);}}
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcdistanceK(root*TreeNode,target*TreeNode,kint)[]int{p:=make(map[*TreeNode]*TreeNode)vis:=make(map[int]bool)varans[]intvarparentsfunc(root,prev*TreeNode)parents=func(root,prev*TreeNode){ifroot==nil{return}p[root]=prevparents(root.Left,root)parents(root.Right,root)}parents(root,nil)vardfsfunc(root*TreeNode,kint)dfs=func(root*TreeNode,kint){ifroot==nil||vis[root.Val]{return}vis[root.Val]=trueifk==0{ans=append(ans,root.Val)return}dfs(root.Left,k-1)dfs(root.Right,k-1)dfs(p[root],k-1)}dfs(target,k)returnans}