forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
all-nodes-distance-k-in-binary-tree.cpp
49 lines (46 loc) · 1.32 KB
/
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
46
47
48
49
// Time: O(n)
// Space: O(n)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {
unordered_map<int, vector<int>> neighbors;
dfs(nullptr, root, &neighbors);
vector<int> bfs{target->val};
unordered_set<int> lookup{target->val};
for (int i = 0; i < K; ++i) {
vector<int> curr;
for (const auto& node : bfs) {
for (const auto& nei : neighbors[node]) {
if (!lookup.count(nei)) {
curr.emplace_back(nei);
lookup.emplace(nei);
}
}
}
swap(bfs, curr);
}
return bfs;
}
private:
void dfs(TreeNode *parent, TreeNode *child,
unordered_map<int, vector<int>> *neighbors) {
if (!child) {
return;
}
if (parent) {
(*neighbors)[parent->val].emplace_back(child->val);
(*neighbors)[child->val].emplace_back(parent->val);
}
dfs(child, child->left, neighbors);
dfs(child, child->right, neighbors);
}
};