Easy to understand -- Graph DFS
It would be very easy to find the neighbors in K distance in an undirected graph, so I convert the tree structure into an undirected graph that a node\'s parent
It would be very easy to find the neighbors in K distance in an undirected graph, so I convert the tree structure into an undirected graph that a node\'s parent and children become it\'s neighbors.\n\nThen a simple DFS algorithm will be very easy to implement on the undirected graph:\n```\nclass Solution {\n    List<Integer> res = new ArrayList<>();\n    List<Integer> visited = new ArrayList<>();\n    GNode target_gnode = null;\n    \n    class GNode {\n        int val;\n        List<GNode> neighbors;\n        GNode(int x) { \n            val = x; \n            neighbors = new ArrayList<GNode>();\n        }\n    }\n    \n    private GNode buildGNodeGraphAndFindTarget(TreeNode tnode, GNode parent, TreeNode target) {\n        GNode gnode = new GNode(tnode.val);\n        if (target_gnode == null && gnode.val == target.val) target_gnode = gnode;\n        if (parent != null) gnode.neighbors.add(parent);\n        if (tnode.left != null) gnode.neighbors.add(buildGNodeGraphAndFindTarget(tnode.left, gnode, target));\n        if (tnode.right != null) gnode.neighbors.add(buildGNodeGraphAndFindTarget(tnode.right, gnode, target));\n        return gnode;\n    }\n    \n    private void DFS(GNode gnode, int k) {\n        if (visited.contains(gnode.val)) return;\n        visited.add(gnode.val);\n        if (k == 0) {\n            if (!res.contains(gnode.val)) res.add(gnode.val);\n            return;\n        }\n        for (GNode neighbor : gnode.neighbors) DFS(neighbor, k - 1);\n    }\n    \n    public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {\n        GNode gnode_root = buildGNodeGraphAndFindTarget(root, null, target);\n        DFS(target_gnode, K);\n        return res;\n    }\n    \n}\n```
[]