-
Notifications
You must be signed in to change notification settings - Fork 0
/
AllNodesDistanceKInBinaryTree.cpp
67 lines (66 loc) · 1.97 KB
/
AllNodesDistanceKInBinaryTree.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* 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:
unordered_map<int, unordered_set<int>> graph;
unordered_map<int, vector<int>> distance;
void buildGraph(TreeNode *root){
if(root==NULL){
return ;
}
int value = root->val;
if(root->left){
int leftValue = root->left->val;
graph[value].insert(leftValue);
graph[leftValue].insert(value);
buildGraph(root->left);
}
if(root->right){
int rightValue = root->right->val;
graph[value].insert(rightValue);
graph[rightValue].insert(value);
buildGraph(root->right);
}
}
vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {
vector<int> res;
buildGraph(root);
int dist = 0;
queue<pair<int, int> > q;
set<int> visited;
q.push(make_pair(target->val, 0));
visited.insert(target->val);
while(!q.empty()){
int x = q.size();
for(int i =0 ; i<x;i++){
auto node = q.front();
int curr = node.first;
int level = node.second;
if(level == K){
while(!q.empty()){
pair<int,int> val = q.front();
cout<<val.first<<" ";
res.push_back(val.first);
q.pop();
}
return res;
}
for(int temp : graph[curr]){
if(visited.find(temp) == visited.end()){
q.push(make_pair(temp, level+1));
visited.insert(temp);
}
}
q.pop();
}
}
return res;
}
};