【前缀思想】二叉树中所有距离为 K 的结点

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

猜你喜欢

转载自www.cnblogs.com/yuelien/p/10532747.html
今日推荐