FAST AND EASY TO UNDERSTAND JAVA
create map for all child to their parents and then apply dfs just like you would in a graph with each node calling its left right and parent\n\n\n/**\n * Defini
create map for all child to their parents and then apply dfs just like you would in a graph with each node calling its left right and parent\n\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) { val = x; }\n * }\n */\nclass Solution {\n    HashMap<TreeNode,TreeNode> map;\n    ArrayList<Integer> arr;\n    TreeNode target;\n    \n    public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {\n        map = new HashMap<>();\n        arr = new ArrayList<>();\n        this.target = target;\n        rec(root);\n        recur(target,K,null);\n        return(arr);\n    }\n    public void rec(TreeNode root){\n        if(root==null){\n            return;\n        }else{\n            if(root.left!=null){\n                map.put(root.left,root);\n            }\n            if(root.right!=null){\n                map.put(root.right,root);\n            }\n            rec(root.left);\n            rec(root.right);\n        }\n    }\n    public void recur(TreeNode start,int k,TreeNode prev){\n        if(start==null){\n            return;\n        }\n        //System.out.println(start.val);\n        if(k==0){\n            \n            arr.add(start.val);\n            return;\n        }else{\n            if(start.left!=prev){\n                recur(start.left,k-1,start);\n            }\n            if(start.right!=prev){\n                recur(start.right,k-1,start);\n            }\n            \n            if(map.containsKey(start)){\n                if(prev!=map.get(start)){\n                    recur(map.get(start),k-1,start);\n                }\n            }\n            return;\n        }\n    }\n}\n```
['Tree', 'Depth-First Search', 'Graph', 'Recursion', 'Java']