力扣(LeetCode)863

https://leetcode-cn.com/probl…

java ac代码：

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
List<Integer> ans = new ArrayList(1000);

HashMap<TreeNode,List<TreeNode>>map = new HashMap(1<<10);
dfs1(root,map);
dfs2(root,map);
ArrayDeque<TreeNode> deque = new ArrayDeque(100);
HashSet<TreeNode>set = new HashSet(1<<10);
HashMap<TreeNode,Integer> map2 = new HashMap(1<<10);
deque.offer(target);
map2.put(target,0);
while(!deque.isEmpty())
{
TreeNode temp = deque.poll();
int num = map2.get(temp)+1;
for(TreeNode node:map.get(temp))
if(!set.contains(node))
{
deque.offer(node);
map2.put(node,num);
}
}
for(Map.Entry<TreeNode,Integer> entry:map2.entrySet())
return ans;

}
void dfs1(TreeNode root,HashMap<TreeNode,List<TreeNode>>map)
{
if(root == null)return;
map.put(root,new ArrayList(100));
dfs1(root.left,map);
dfs1(root.right,map);
}

void dfs2(TreeNode root,HashMap<TreeNode,List<TreeNode>>map)
{
if(root == null)return;
if(root.left != null)
{

}
if(root.right != null)
{
}
dfs2(root.left,map);
dfs2(root.right,map);

}

}``````
原文作者：Linus脱袜子
原文地址: https://segmentfault.com/a/1190000017933565
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。