🏆C++ || Tree Dfs
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 
# 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    vector<int>a;\n    void depth(TreeNode* root,int k){\n        if(!root)return;\n        if(k==0)a.push_back(root->val);\n        depth(root->left,k-1);\n        depth(root->right,k-1);\n    }\n    int c(TreeNode* root,TreeNode* target,int k){\n        if(!root){\n            return -1;\n        }\n        if(root==target){\n            depth(root,k);\n            return 0;\n        }\n        int leftd = c(root->left,target,k);\n        if(leftd!=-1){\n            if(leftd+1==k){\n                a.push_back(root->val);\n            }\n            else{\n                depth(root->right,k-leftd-2);\n            }\n            return 1+leftd;\n        }\n        int rightd = c(root->right,target,k);\n        if(rightd!=-1){\n             if(rightd+1==k){\n                a.push_back(root->val);\n            }\n            else{\n                depth(root->left,k-rightd-2);\n            }\n            return 1+rightd;\n        }\n        return -1;\n    }\n    vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {\n        c(root,target,k);\n        return a;\n    }\n};\n```\n![upvote (2).jpg](https://assets.leetcode.com/users/images/914167b0-15d4-48f7-af43-f80abd565c91_1689050699.697932.jpeg)\n
['Tree', 'Depth-First Search', 'Binary Tree', 'C++']