Clean Code | C++ |  0ms  |  DFS
Approach\n\nWe know that we can find the nodes that are k distance below just by using recursion and by iterating over the same.\n\nbut for those nodes which ar
Approach\n\nWe know that we can find the nodes that are k distance below just by using recursion and by iterating over the same.\n\nbut for those nodes which are above the current one or which are siblings of the target node, we have to use node to root path as helper array and then make calls according to that.\n\n```\nclass Solution {\npublic:\n    \n    vector<TreeNode*>nodePath(TreeNode* root,TreeNode*target){\n        \n        if(root == NULL)\n            return {};\n    \n        if(root->val ==target->val)\n            return {root};\n        \n        vector<TreeNode*>ans;\n        \n        ans = nodePath(root->left,target);\n        \n        if(ans.size()>0){\n            ans.push_back(root);\n            return ans ;\n        }\n        \n        ans = nodePath(root->right,target);\n        \n        if(ans.size()>0){\n            ans.push_back(root);\n            return ans;\n        }\n        \n        return {};\n        \n    }\n    \n    vector<int>ans;\n    \n    void findDown(TreeNode* root,int k,int level){\n        \n        if(root == NULL)\n            return;\n        \n        if(k==level){\n            ans.push_back(root->val);\n            return;\n        }\n        \n        findDown(root->left,k,level+1);\n        findDown(root->right,k,level+1);\n        \n    }\n    \n    void findNodes(TreeNode* root,int level,int k, TreeNode* danger){\n        \n        if(root == NULL)\n            return ;\n        \n        if(root == danger)\n            return ;\n        \n        if(level == k){\n            ans.push_back(root->val);\n            return;\n        }\n        \n        findNodes(root->left,level+1,k,danger);\n        findNodes(root->right,level+1,k,danger);\n        \n    }\n    \n    vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {\n        \n        vector<TreeNode*>path = nodePath(root,target);\n        \n        findDown(path[0],k,0);\n        \n        for(int ctr = 1 ; ctr < path.size();ctr++){\n            findNodes(path[ctr],0,k-ctr,path[ctr-1]);\n        }\n        \n        return ans ;\n        \n    }\n};\n```
['Depth-First Search', 'C']