Skip to content

Commit 3475cf8

Browse files
committed
Thoda bhot hi samajh aya, will revisit it again.
1 parent 572219c commit 3475cf8

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
class Solution {
2+
public:
3+
vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
4+
vector<int> ans;
5+
unordered_map<int, TreeNode*> parent;
6+
queue<TreeNode*> q;
7+
q.push(root);
8+
9+
while(!q.empty()){
10+
int si = q.size();
11+
for(int i = 0; i < si; i++){
12+
auto top = q.front();
13+
q.pop();
14+
15+
if(top -> left){
16+
parent[top->left->val] = top;
17+
q.push(top->left);
18+
}
19+
20+
if(top -> right){
21+
parent[top->right->val] = top;
22+
q.push(top->right);
23+
}
24+
}
25+
}
26+
27+
unordered_map<int, int> visited;
28+
q.push(target);
29+
while(k-- && !q.empty()){
30+
int size = q.size();
31+
32+
for(int i = 0; i < size; i++){
33+
auto top = q.front();
34+
q.pop();
35+
36+
visited[top -> val] = 1;
37+
38+
if(top -> left && !visited[top->left->val]){
39+
q.push(top -> left);
40+
}
41+
42+
if(top -> right && !visited[top->right->val]){
43+
q.push(top -> right);
44+
}
45+
46+
if(parent[top->val] && !visited[parent[top->val] -> val]){
47+
q.push(parent[top->val]);
48+
}
49+
50+
}
51+
}
52+
53+
while(!q.empty()){
54+
ans.push_back(q.front()->val);
55+
q.pop();
56+
}
57+
return ans;
58+
}
59+
};

0 commit comments

Comments
 (0)