继上篇文章的感染二叉树之后的,leecode中和该题类似的题目
和上次的题还是一模一样,一样的步骤
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Map<TreeNode,TreeNode> parents=new HashMap();
TreeNode targetNode;
Set<TreeNode> sites=new HashSet();
public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
findParents(root,null,target);
List<Integer> res=new ArrayList();
if(K==0){
res.add(target.val);
return res;
}
Deque<TreeNode> deque=new LinkedList();
deque.offer(targetNode);
int len=0;
while(!deque.isEmpty()){
len++;
int size=deque.size();
while(size>0){
TreeNode temp=deque.poll();
sites.add(temp);
if(temp.left!=null&&!sites.contains(temp.left)){
if(len==K){
res.add(temp.left.val);
}
deque.offer(temp.left);
}
if(temp.right!=null&&!sites.contains(temp.right)){
if(len==K){
res.add(temp.right.val);
}
deque.offer(temp.right);
}
if(parents.get(temp)!=null&&!sites.contains(parents.get(temp))){
if(len==K){
res.add(parents.get(temp).val);
}
deque.offer(parents.get(temp));
}
size--;
}
if(len==K){
break;
}
}
return res;
}
//找到父亲节点
public void findParents(TreeNode root,TreeNode parent,TreeNode target){
if(root==null){
return ;
}
if(root.val==target.val){
targetNode=root;
}
parents.put(root,parent);
findParents(root.left,root,target);
findParents(root.right,root,target);
}
}