python dfs O(n)
python\nclass Solution:\n    def distanceK(self, root, target, K):\n        """\n        :type root: TreeNode\n        :type target: TreeNode\n        :type K: 
```python\nclass Solution:\n    def distanceK(self, root, target, K):\n        """\n        :type root: TreeNode\n        :type target: TreeNode\n        :type K: int\n        :rtype: List[int]\n        """\n        d = {}\n        # get the distances from ancestors to target\n        def dis(node):\n            if node in d: return d[node]\n            if not node: return -1\n            if node == target: \n                d[node] = 0\n                return 0\n            l = dis(node.left)\n            if l != -1:\n                d[node] = l + 1\n                return l + 1\n            r = dis(node.right)\n            if r != -1:\n                d[node] = r + 1\n                return r + 1\n            return -1\n        dis(root)\n        res = []\n        # get the final result, update cur if node is in d\n        def helper(node, cur):\n            if not node: return\n            if node in d: cur = d[node]\n            if cur == K: res.append(node.val)\n            helper(node.left, cur + 1)\n            helper(node.right, cur + 1)\n        helper(root, 0)\n        return res\n```
[]