Java BFS solution | O(n) time | O(n) space
The intuition in this question is to think the tree to be a directed graph where the parent is pointing to it\'s children.\n1. We need to convert this directed 
1. The intuition in this question is to think the tree to be a directed graph where the parent is pointing to it\'s children.\n1. We need to ***convert this directed graph to an undirected graph*** and perform BFS on this undirected graph.\n1. For making the tree as undirected graph we would want an edge from a node to it\'s parent-> We achieve this with the help of auxiliary memory in the form of Map<TreeNode, TreeNode> parent.\n2. After the conversion to an undirected graph-> we perform a standard BFS.\n\n```\n public List<Integer> distanceK(TreeNode root, TreeNode target, int K) { //O(n)\n        List<Integer> ans=new ArrayList<>();\n        if(root==null)return ans;\n        \n        //hashmap to store child-parent pair\n        HashMap<TreeNode, TreeNode> parent=new HashMap<>();\n        getParents(root, parent);\n       \n        \n        //to keep a track of visited nodes.\n        //this is needed because there can be nodes visited more than once\n        //considering we are performing BFS on chhildrens and parent both\n        Set<TreeNode> visited=new HashSet<>();\n        \n        Queue<TreeNode> q=new LinkedList<>();\n        q.add(target);\n        \n        int level=0;\n        while(!q.isEmpty()){\n            int size=q.size();\n            for(int i=0;i<size;i++){\n                TreeNode node=q.poll();\n                \n                //if removed node is null or is already visited\n                if (node == null || visited.contains(node)) continue;\n                \n                //mark the node as visited\n                visited.add(node);\n                \n                //add nodes when level is \'K\' starting from \'start\' node\n                if(level==K){\n                    ans.add(node.val);\n                }\n                    q.add(node.left);\n                    q.add(node.right);\n                    q.add(parent.get(node));\n                \n                }\n                level++;\n            }\n        return ans;\n    }\n    \n    //func to compute the parent of the nodes recursively\n    public void getParents(TreeNode root, HashMap<TreeNode, TreeNode> parent){ //O(n)\n        if(root==null)return;\n        \n        if(root.left!=null)parent.put(root.left, root);\n        if(root.right!=null)parent.put(root.right, root);\n        getParents(root.left, parent);\n        getParents(root.right, parent);\n    }\n```
['Breadth-First Search', 'Java']