O (1) Space complexity and TC O( N )
const int INF =   INT_MAX;\nclass Solution {\npublic:\n\n    void search(TreeNode * root, int k, vector&ans){\n        if(!root) return ;\n        if(k==0){\n  
const int INF =   INT_MAX;\nclass Solution {\npublic:\n\n    void search(TreeNode * root, int k, vector<int>&ans){\n        if(!root) return ;\n        if(k==0){\n            ans.push_back(root->val);\n            return;\n        }\n        \n        search(root->left,k-1,ans);\n        search(root->right,k-1,ans);\n    }\n    int find(TreeNode * root, TreeNode * target, int k, vector<int>&ans){\n        if(!root) return INF;\n        if(root==target){\n\t\t\n            search(root,k,ans);\n            return 0;\n        }\n        int left = find(root->left,target,k,ans);\n        if(left!=INT_MAX){\n              if(k==1+left) ans.push_back(root->val);\n            else {\n                search(root->right,k-(left+1)-1,ans);\n            }\n            return 1 + left;\n        }\n        int right = find(root->right,target,k,ans);\n        if(right!=INT_MAX){\n            \n            if(1+right==k) ans.push_back(root->val);\n            else {\n                search(root->left,k-(right+1)-1,ans);\n            }\n            return 1 + right;\n        }      \n        \n        return INF;\n    }\n    vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {\n        vector<int>ans;\n       find(root,target,k,ans);\n        return ans;\n    }\n};
['Recursion', 'C++']