-
Notifications
You must be signed in to change notification settings - Fork 0
/
Nodes at given distance in binary tree.cpp
67 lines (67 loc) · 1.87 KB
/
Nodes at given distance 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
55
56
57
58
59
60
61
62
63
64
65
66
67
class solver{
private:
public:
void make_map(Node * root,map<Node*,Node*>&mp){
if(root==NULL){
return;
}
mp[root->left]=root;
mp[root->right]=root;
make_map(root->left,mp);
make_map(root->right,mp);
}
vector<int> distanceK(Node* root, Node* target, int k) {
vector<int>V;
map<Node *,Node *>mp;
make_map(root,mp);
queue<Node*>Q;
Q.push(target);
int count=0;
vector<int>check(10000,0);
while(!Q.empty()){
int size=Q.size();
while(size--){
Node* temp=Q.front();
Q.pop();
if(count==k){
V.push_back(temp->data);
}
else {
check[temp->data]=1;
if(temp->left && check[temp->left->data]==0 ){
Q.push(temp->left);
}
if(temp->right && check[temp->right->data]==0 ){
Q.push(temp->right);
}
if(mp.find(temp)!=mp.end() && check[mp[temp]->data]==0 ){
Q.push(mp[temp]);
}
}
}
count++;
}
return V;
}
void findthetarget(Node*root,int target,Node * & result){
if(root==NULL){
return ;
}
if(root->data==target){
result=root;
return ;
}
findthetarget(root->left,target,result);
findthetarget(root->right,target,result);
return ;
}
vector <int> KDistanceNodes(Node* root, int target , int k){
Node *result=NULL;
findthetarget(root,target,result);
Node * ans=result;
vector<int>V;
V=distanceK(root,ans,k);
sort(V.begin(),V.end());
return V;
}
};