BFS & DFS JS Solutions
\nvar distanceK = function(root, target, K) {\n    let m = new Map();\n    let queue = [root];\n    while (queue.length > 0) {\n        let node = queue.shift()
```\nvar distanceK = function(root, target, K) {\n    let m = new Map();\n    let queue = [root];\n    while (queue.length > 0) {\n        let node = queue.shift();\n        if (node.left) {\n            m.set(node.left, node);\n            queue.push(node.left);\n        }\n        if (node.right) {\n            m.set(node.right, node);\n            queue.push(node.right);\n        }\n    }\n    // (key, value) in m is (child, parent)\n    \n    let values = [], visited = new Map();\n    queue = [{node: target, distance: 0}];\n    \n    while (queue.length > 0) {\n        let {node, distance} = queue.shift();\n        // if (visited.has(node)) continue;\n        // we don\'t need this line but you can have it to play safe\n        visited.set(node, 1);\n        \n        if (distance == K) {\n            values.push(node.val);\n            continue; // optimisation\n        }\n\n        if (node.left && !visited.has(node.left)) {\n            queue.push({node: node.left, distance: distance+1});\n        }\n        if (node.right && !visited.has(node.right)) {\n            queue.push({node: node.right, distance: distance+1});\n        }\n        if (m.has(node) && !visited.has(m.get(node))) {\n            queue.push({node: m.get(node), distance: distance+1});\n        }\n    }\n    return values;\n    // Time Complexity: O(n)\n    // Space Complexity: O(n)\n};\n```\n\n```\nvar distanceK = function(root, target, K) {\n    let m = new Map(), visited = new Map(), res = [];\n    // (key, value) in m represents (node, parent)\n    traverse(root, m, visited);\n    findNodes(target);\n    return res;\n    \n    function findNodes(root, distance=0) {\n        if (!root || visited.get(root)) return;\n        if (distance == K) {\n            res.push(root.val);\n            return;\n        }\n        visited.set(root, true);\n        if (m.has(root)) {\n            findNodes(m.get(root), distance + 1);\n        }\n        findNodes(root.left, distance + 1);\n        findNodes(root.right, distance + 1);\n    }\n    // Time Complexity: O(n)\n    // Space Complexity: O(n)\n};\n\nfunction traverse(root, map, visited) {\n    if (!root) return;\n    visited.set(root, false);\n    if (root.left) {\n        map.set(root.left, root);\n        traverse(root.left, map, visited);\n    }\n    if (root.right) {\n        map.set(root.right, root);\n        traverse(root.right, map, visited);\n    }\n}\n```
['JavaScript']