C++ build graph and BFS //commented
\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : v
```\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    //directed acyclic graph to undirected acyclic graph\n    void buildGraph(TreeNode* root,unordered_map<int,vector<int>>& graph){\n        \n        if(root->left!=NULL){\n            graph[root->val].push_back(root->left->val);\n            graph[root->left->val].push_back(root->val);\n            buildGraph(root->left,graph);\n        }\n        if(root->right!=NULL){            \n            graph[root->val].push_back(root->right->val);\n            graph[root->right->val].push_back(root->val);\n            buildGraph(root->right,graph);            \n        }\n    }\n    \n    \n    vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {\n        \n        if(K==0)\n            return {target->val};\n        \n        //initialisation \n        \n        unordered_map<int,vector<int>> graph; //graph\n        unordered_map<int,bool> visited;\n        vector<int> res;\n        queue<int> q;\n        int cnt = 0;\n        \n        //build the graph\n        buildGraph(root,graph);\n        \n        //push the target to start bfs with\n        q.push(target->val);\n        \n        //bfs\n        while(!q.empty()){\n            int sz = q.size();\n            for(int i=0;i<sz;i++){\n                \n                int curr = q.front();\n                q.pop();\n                visited[curr]=true;\n                \n                for(int x : graph[curr])\n                    if(!visited[x])\n                        q.push(x);\n            }\n            cnt++;\n            //we reached the Kth layer, push the layer in res vector and break bfs\n            if(cnt==K){\n                while(!q.empty()){\n                    res.push_back(q.front());\n                    q.pop();\n                }\n                break;\n            }\n                \n        }\n        \n        return res;\n    }\n};\n```
['Breadth-First Search', 'Graph', 'C', 'C++']