Simplest C++ Solution || beats 100% || Go up, left & right
Code\n\nclass Solution {\npublic:\n    void dfs(TreeNode* root,unordered_map<TreeNode*,TreeNode*>& parent,TreeNode* prev){\n        if(!root) return;\n        p
# Code\n```\nclass Solution {\npublic:\n    void dfs(TreeNode* root,unordered_map<TreeNode*,TreeNode*>& parent,TreeNode* prev){\n        if(!root) return;\n        parent[root]=prev;\n        dfs(root->left,parent,root);\n        dfs(root->right,parent,root);\n    }\n\n    void help(TreeNode* root,unordered_map<TreeNode*,TreeNode*>& parent,bool l,bool r,bool up,int k,vector<int>& ans){\n        if(!root) return;\n        if(k==0){\n            ans.push_back(root->val);\n            return;\n        }\n        \n        if(l) help(root->left,parent,1,1,0,k-1,ans);\n        if(r) help(root->right,parent,1,1,0,k-1,ans);\n        if(up && parent[root]!=NULL){\n            if(parent[root]->left==root) help(parent[root],parent,0,1,1,k-1,ans); \n            else help(parent[root],parent,1,0,1,k-1,ans);\n        }\n    }\n\n    vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {\n        unordered_map<TreeNode*,TreeNode*> parent;\n        dfs(root,parent,NULL);\n        vector<int> ans;\n        help(target,parent,1,1,1,k,ans);\n        return ans;\n    }\n};\n```
['Hash Table', 'Tree', 'Depth-First Search', 'Binary Tree', 'C++']