Simple Solution beats 100% memory and 100% time without any extra data structure
\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : v
```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nvoid nodeskdistance(TreeNode* target, int K, vector<int> &ans){\n    if(target==NULL){\n        return;\n    }\n    if(K==0){\n        ans.push_back(target->val);\n        return;\n    }\n    nodeskdistance(target->left, K-1, ans);\n    nodeskdistance(target->right, K-1, ans);\n}\nbool findNode(TreeNode* root, TreeNode* target, int &K, vector<int> &ans){\n    if(root==NULL){\n        return false;\n    }\n    if(root==target){\n        nodeskdistance(target, K, ans);\n        return true;\n    }\n    bool ifleft = findNode(root->left, target,K, ans);\n    bool ifright = findNode(root->right, target, K, ans);\n    if(ifleft){\n        --K; // decrese the distance now as parent will be at 1 distance now from the target.\n        if(K<0){\n            return true; //if the ancestor is more than k distance away from the parent\n        }\n        if(K==0){\n            ans.push_back(root->val);\n            return true;\n        }\n        nodeskdistance(root->right, K-1, ans); //search in right subtree for nodes at a distance k\n        return true;\n    }\n    if(ifright){\n        --K;\n        if(K<0){\n            return true; //if the ancestor is more than k distance away from the parent\n        }\n        if(K==0){\n            ans.push_back(root->val);\n            return true;\n        }\n        nodeskdistance(root->left, K-1, ans); //search in left subtree for nodes at a distance k\n        return true;\n    }\n    return false;\n}\nclass Solution {\npublic:\n    vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {\n        vector<int> ans;\n        findNode(root, target, K, ans);\n        return ans;\n    }\n};\n```
[]