forked from Michael-Calce/GeeksForGeeks-Problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path11 July Find kth element of spiral matrix
80 lines (80 loc) · 2.25 KB
/
11 July Find kth element of spiral matrix
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
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* 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:
void getparentbyBFS(unordered_map<TreeNode*,TreeNode*>&parent,TreeNode*root){
queue<TreeNode*>q;
q.push(root);
while(!q.empty()){
int n=q.size();
while(n--){
TreeNode*curr=q.front();
q.pop();
if(curr->left){
parent[curr->left]=curr;
q.push(curr->left);
}
if(curr->right){
parent[curr->right]=curr;
q.push(curr->right);
}
}
}
}
void getparentbyDFS(unordered_map<TreeNode*,TreeNode*>&parent,TreeNode*root){
if(root==NULL)
return;
if(root->left!=NULL){
parent[root->left]=root;
}
if(root->right!=NULL){
parent[root->right]=root;
}
getparentbyDFS(parent,root->left);
getparentbyDFS(parent,root->right);
}
vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
unordered_map<TreeNode*,TreeNode*>parent;
getparentbyDFS(parent,root);
queue<TreeNode*>q;
unordered_map<TreeNode*,bool>vis;
vis[target]=true;
q.push(target);
int lev=0;
while(!q.empty()){
int n=q.size();
if(lev==k)
break;
lev++;
while(n--){
TreeNode*curr=q.front();
q.pop();
if(curr->left&&!vis[curr->left]){
vis[curr->left]=true;
q.push(curr->left);
}
if(curr->right&&!vis[curr->right]){
vis[curr->right]=true;
q.push(curr->right);
}
if(parent[curr]&&!vis[parent[curr]]){
vis[parent[curr]]=true;
q.push(parent[curr]);
}
}
}
vector<int>ans;
while(q.size()>0){
ans.push_back(q.front()->val);
q.pop();
}
return ans;
}
};