Easy to understand Code using basic basic tree logic C++ 4ms
Approach:\n\n We find the path of the node to root.\n Traverse the node path and reduce the value of k accordingly.\n* add all the node (k - i) distance down wh
### Approach:\n\n* We find the path of the node to root.\n* Traverse the node path and reduce the value of k accordingly.\n* add all the node (k - i) distance down while making sure to not go back on our previous node in the path. \n\n```\nvector<TreeNode*> rootToNodePath(TreeNode *root, TreeNode *target)\n{\n\tvector<TreeNode*> ans;\n\n\tif(!root) return ans;\n\n\tif(root == target)\n\t{\n\t\tans.push_back(root);\n\t\treturn ans;\n\t}\n\n\tvector<TreeNode*> leftPath = rootToNodePath(root->left, target);\n\n\tif(leftPath.size() > 0)\n\t{\n\t\tleftPath.push_back(root);\n\n\t\treturn leftPath;\n\t}\n\n\tvector<TreeNode*> rightPath = rootToNodePath(root->right, target);\n\n\tif(rightPath.size() > 0)\n\t{\n\t\trightPath.push_back(root);\n\n\t\treturn rightPath;\n\t}\n\n\treturn ans;\n}\n\nTreeNode *badNode; \n\nvoid kNodesDown(TreeNode *root, int level, int k, vector<int> &ans)\n{\n\tif(!root || root == badNode) return;\n\n\tif(level == k)\n\t{\n\t\tans.push_back(root->val);\n\t}\n\n\tkNodesDown(root->left, level + 1, k, ans);\n\tkNodesDown(root->right, level + 1, k, ans);\n}\n\nvector<int> distanceK(TreeNode* root, TreeNode* target, int k) \n{\n\tvector<TreeNode*> path = rootToNodePath(root, target); //the path from node to root\n\n\tvector<int> ans;\n\n\tint size = path.size();\n\n\tfor(int index = 0; index < size; index++) //we find the nodes k level down depending on the current index\n\t{\n\t\tif(index == 0) badNode = NULL;\n\t\telse badNode = path[index - 1];\n\n\t\tkNodesDown(path[index], 0, k, ans);\n\t\tk--;\n\t}\n\n\treturn ans;\n}\n```\n\nPS : I am learning and trying to help the community ! Still not sure if my solution is the best one, even after 0ms. Feel free to give your suggestions or correct me in the comments. Thanks for reading.
['C']