-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path863.cpp
More file actions
41 lines (41 loc) · 1.2 KB
/
Copy path863.cpp
File metadata and controls
41 lines (41 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public:
vector<int> distanceK(TreeNode *root, TreeNode *target, int K) {
unordered_map<int, vector<int>> graph;
unordered_set<int> tra;
queue<TreeNode *> que;
que.push(root);
while (!que.empty()) {
root = que.front();
que.pop();
if (root->left) {
graph[root->val].push_back(root->left->val);
graph[root->left->val].push_back(root->val);
que.push(root->left);
}
if (root->right) {
graph[root->val].push_back(root->right->val);
graph[root->right->val].push_back(root->val);
que.push(root->right);
}
}
vector<int> ret;
vector<int> v;
ret.push_back(target->val);
int size = 1;
while (K > 0) {
for (auto iter:ret) {
for (auto i : graph[iter]) {
if (tra.find(i) != tra.end())
continue;
v.push_back(i);
}
tra.insert(iter);
}
ret = v;
v.clear();
--K;
}
return ret;
}
};