Simple JS Solution w/ Comments - DFS
\n/**\n * DFS - Parent Mapping\n * *Time: O(N)\n * *Space: O(N)\n */\n// Runtime: 84 ms, faster than 71.81% of JavaScript online submissions for All Nodes Dista
```\n/**\n * DFS - Parent Mapping\n * *Time: O(N)\n * *Space: O(N)\n */\n// Runtime: 84 ms, faster than 71.81% of JavaScript online submissions for All Nodes Distance K in Binary Tree.\n// Memory Usage: 40.8 MB, less than 60.90% of JavaScript online submissions for All Nodes Distance K in Binary Tree.\nconst distanceK = (root, target, k) => {\n\tconst parent = new Map(); // children: parent\n\t\n\t// map children to parent\n\t// this is so we can traverse "up" from our given target node\n\tconst traverse = root => {\n\t\tif (!root) return;\n\n\t\tif (root.left) {\n\t\t\tparent.set(root.left, root);\n\t\t\ttraverse(root.left);\n\t\t}\n\n\t\tif (root.right) {\n\t\t\tparent.set(root.right, root);\n\t\t\ttraverse(root.right);\n\t\t}\n\t};\n\n\tconst output = [];\n\tconst visited = new Set();\n\tconst findNodes = (root, distance) => {\n\t\tif (!root) return;\n\t\tif (visited.has(root)) return;\n\t\tif (distance === k) output.push(root.val); // k-distance node found\n\n\t\tvisited.add(root); // mark visited\n\t\t\n\t\t// traverse left/right and "up" parent\n\t\tfindNodes(root.left, distance + 1); // left\n\t\tfindNodes(root.right, distance + 1); // right\n\t\tfindNodes(parent.get(root), distance + 1); // parent\n\t};\n\n\ttraverse(root);\n\tfindNodes(target, 0);\n\treturn output;\n};\n\n```
['Depth-First Search', 'JavaScript']