class Solution { Map<TreeNode,String>map=new HashMap<>(); String path; void getNodeDist(TreeNode root,TreeNode target,String p){ if(root!=null){ path=root==target?p:path; map.put(root, p); getNodeDist(root.left,target,p+"0"); getNodeDist(root.right,target,p+"1"); } } public List<Integer> distanceK(TreeNode root, TreeNode target, int K) { List<Integer>list=new ArrayList<>(); getNodeDist(root,target,"");int i; for(TreeNode key:map.keySet()){ String s=map.get(key); for(i=0;i<s.length()&&i<path.length()&&s.charAt(i)==path.charAt(i);i++); if(s.length()-i+path.length()-i==K) list.add(key.val); } return list; } }
受hash编码启发的一个很简单的实现方法,脑筋急转弯题23333