图论16(Leetcode863.二叉树中所有距离为K的结点)

答案:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List distanceK(TreeNode root, TreeNode target, int k) {
        Map map = new HashMap<>();
        int[] link = {-1,-1,-1};
        map.put(root.val,link);
        Queue queue = new LinkedList<>();
        queue.add(root);
        while(queue.size()!=0){
            TreeNode cur = queue.poll();
            int[] link1 = new int[3];
            int[]temp = map.get(cur.val);//cur包含父节点的link
            link1[0] = temp[0];
            link1[1] = -1;
            link1[2] = -1;
            int[] link2 = {cur.val,-1,-1};//记录left right的父节点
            if(cur.left!=null){
                TreeNode left = cur.left;
                link1[1] = left.val;
                map.put(left.val,link2);
                queue.add(left);

            }
            if(cur.right!=null){
                TreeNode right = cur.right;
                link1[2] = right.val;
                map.put(right.val,link2);
                queue.add(right);
            }
            map.put(cur.val,link1);
        }

        map.forEach((key, value) -> System.out.println("Key = " + key + ", Value = " + value[0] +" "+ value[1]+" "+ value[2]));


        List res = new ArrayList<>();
        Queue queue2 = new LinkedList<>();
        Set set = new HashSet<>();
        queue2.add(target.val);
        set.add(target.val);
        int step = 0;
        while(queue2.size()!=0){
            if(step==k){
                while(queue2.size()!=0){
                    res.add(queue2.poll());
                }
                break;
            }
            int len = queue2.size();
            for(int i=0;i

你可能感兴趣的:(图论)