Beats 99% of Users in Space Complexity. O(1) Space...
\n\n# Complexity\n- Time complexity:\n- O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:\n- O(1)\n Add your space complexity here, e.g. O
\n\n# Complexity\n- Time complexity:\n- O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\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 */\nclass Solution {\npublic:\n    int levelOfTarget = 0;\n    vector<int> res;\n    void dfs0(TreeNode* node, TreeNode* target, int lvl) {\n        if(node == NULL) {\n            return;\n        }\n        if(node == target) {\n            levelOfTarget = lvl;\n            return;\n        }\n        dfs0(node -> left, target, lvl + 1);\n        dfs0(node -> right, target, lvl + 1);\n    }\n\n    void dfs1(TreeNode* node, int lvl, int want) {\n        if(node == NULL) {\n            return;\n        }\n        if(lvl == want) {\n            res.push_back(node->val);\n            return;\n        }\n        dfs1(node -> left, lvl + 1, want);\n        dfs1(node -> right, lvl + 1, want);\n    }\n\n    int KK;\n    bool dfs(TreeNode* node, TreeNode* target, int lvl) {\n        if(node == NULL) {\n            return false;\n        }\n\n        if(lvl > levelOfTarget) {\n            return false;\n        }\n        \n        if(node == target) {\n            dfs1(node -> left, 1, KK);\n            dfs1(node -> right, 1, KK);\n            return 1;\n        }\n\n        int c1 = dfs(node->left, target, lvl + 1);\n        int c2 = dfs(node->right, target, lvl + 1);\n\n        if(c1 == false && c2 == true) {\n            int alreadyDone = (levelOfTarget - lvl);\n            if(alreadyDone == KK) {\n                res.push_back(node->val);\n            }\n            if(alreadyDone < KK) {\n                dfs1(node->left, 1, KK - alreadyDone);\n            }\n        }\n        if(c2 == false && c1 == true) {\n            int alreadyDone = (levelOfTarget - lvl);\n            if(alreadyDone == KK) {\n                res.push_back(node->val);\n            }\n            if(alreadyDone < KK) {\n                dfs1(node->right, 1, KK - alreadyDone);\n            }\n        }\n\n        return c1 | c2;\n    }\n    vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {\n        KK = k;\n        if(k == 0) {\n            return {target->val};\n        }\n        res.clear();\n        dfs0(root, target, 0);\n        dfs(root, target, 0);\n        return res;\n\n    }\n};\n```
['C++']