Elegant Python DFS solution
\nclass Solution(object):\n    def distanceK(self, root, target, K):\n        \n        # dfs preorder traversal to map each node to its parent\n        def get
```\nclass Solution(object):\n    def distanceK(self, root, target, K):\n        \n        # dfs preorder traversal to map each node to its parent\n        def get_parent(node = root, parent = None):\n            if not node: return\n            hashmap[node] = parent\n            get_parent(node.left, node), get_parent(node.right, node)\n        \n        def search(node = target, distance = 0):\n            if not node or node.val in visited: return\n            visited.add(node.val)\n            if distance == K: answer.append(node.val)\n            for neighbour in (hashmap[node], node.left, node.right):\n                search(neighbour, distance+1)\n        \n        hashmap, answer, visited = {}, [], set()\n        get_parent(), search()\n        return answer\n```
['Depth-First Search', 'Recursion', 'Python']