- Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathall-nodes-distance-k-in-binary-tree.cpp
45 lines (36 loc) · 962 Bytes
/
all-nodes-distance-k-in-binary-tree.cpp
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
42
43
44
45
//Runtime: 7 ms
classSolution {
public:
voidtoGraph(TreeNode* root, map<int, vector<int> >&adj) {
vector<int> t;
if (root->left) {
adj[root->val].push_back(root->left->val);
adj[root->left->val].push_back(root->val);
toGraph(root->left, adj);
}
if (root->right) {
adj[root->val].push_back(root->right->val);
adj[root->right->val].push_back(root->val);
toGraph(root->right, adj);
}
}
voiddfs(map<int, vector<int> >&adj, int tar, int dis, vector<int> &res, set<int> &vis) {
if (vis.find(tar) != vis.end()) return;
if (dis == 0) res.push_back(tar);
if (dis <= 0) return;
if (vis.find(tar) == vis.end()) {
vis.insert(tar);
for (int a : adj[tar]) {
dfs(adj, a, dis - 1, res, vis);
}
}
}
vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {
map<int, vector<int> > adj;
toGraph(root, adj);
vector<int> res;
set<int> vis;
dfs(adj, target->val, K, res, vis);
return res;
}
};