首页 > 其他 > 详细

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

时间:2019-03-14 19:49:03      阅读:181      评论:0      收藏:0      [点我收藏+]

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 的结点

原文:https://www.cnblogs.com/yuelien/p/10532747.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!