题目链接
思路:变相的深搜,也就是将父节点也加进去进行深度遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> distanceK_res = new ArrayList<>();//记录答案
HashMap<Integer, TreeNode> distanceK_map = new HashMap<>();//记录父节点 node -> parent
boolean[] flags = new boolean[501];// 记录是否被用过了
public List<Integer> distanceK(TreeNode root, TreeNode target, int k) {
if(k <= 500){
distanceKHelper1(root);
distanceKHelper2(target, k);
}
return distanceK_res;
}
public void distanceKHelper2(TreeNode target, int k){
flags[target.val] = true;
if(k==0){
distanceK_res.add(target.val);
return;
}
if( target.left != null && !flags[target.left.val]){
flags[target.left.val] = true;
distanceKHelper2(target.left, k-1);
}
if(target.right != null && !flags[target.right.val]){
flags[target.right.val] = true;
distanceKHelper2(target.right, k-1);
}
TreeNode parent = distanceK_map.get(target.val);
if( parent!= null && !flags[parent.val]){
distanceKHelper2(parent, k-1);
}
}
public void distanceKHelper1(TreeNode root){
if(root.left != null){
distanceK_map.put(root.left.val, root);
distanceKHelper1(root.left);
}
if(root.right != null){
distanceK_map.put(root.right.val, root);
distanceKHelper1(root.right);
}
}
}