-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAll nodes distance at k in binary tree.cpp
54 lines (54 loc) · 1.57 KB
/
All nodes distance at 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
50
51
52
53
54
/**
* 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<TreeNode*, TreeNode*> mp;
void dfs(TreeNode* root, TreeNode* parent){
if(!root) return;
if(!parent) parent = root;
else mp[root] = parent;
dfs(root->left, root);
dfs(root->right, root);
}
vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
queue<TreeNode*> q;
set<TreeNode*> st;
dfs(root,NULL);
q.push(target);
int cnt=0;
vector<int> res;
while(!q.empty()){
int sz=q.size();
if(cnt>k) break;
while(sz--){
auto node=q.front();
q.pop();
if(node->left!=NULL and !st.count(node->left)){
q.push(node->left);
st.insert(node->left);
}
if(node->right!=NULL and !st.count(node->right)){
q.push(node->right);
st.insert(node->right);
}
if(mp.count(node) and !st.count(mp[node])){
q.push(mp[node]);
st.insert(mp[node]);
}
st.insert(node);
if(cnt==k){
res.push_back(node->val);
}
}
cnt++;
}
return res;
}
};