【前綴思想】二叉樹中所有距離為 K 的結點
阿新 • • 發佈:2019-03-14
right 前綴 amp add ger integer 思想 length 簡單
863. 二叉樹中所有距離為 K 的結點
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
【前綴思想】二叉樹中所有距離為 K 的結點